• python装饰器的简单实用


    装饰器(Decorators)可以实现在不变原有python 代码功能的基础上增加功能代码。

    框架

    def outer2(func):
        def inner(*args, **kwargs):
            func(*args, **kwargs)
        return inner
    
    
    @outer2
    def foo(a, b, c):
        print (a+b+c)
    

      

    示例一:

    import time
    from functools import wraps
    
    
    def time_checker(func):
        @wraps(func)
        def inner(*args, **kwargs):
            time_start = time.time()
            ret = func(*args, **kwargs)
            print(f'{func.__name__} running time is {time.time() - time_start} 秒')
            return ret
        return inner
    
    
    @time_checker
    def func1():
        time.sleep(1)
        print(f'now func1 is  running')
    
    
    if __name__ == '__main__':
        func1()
    

     示例二:

    from functools import wraps
    
    
    def logit(logfile='out.log'):
        def logging_decorator(func):
            @wraps(func)
            def wrapped_functions(*args, **kwargs):  
                log_string = func.__name__ + ' was called'
                print(log_string)
                with open(logfile, 'a') as opend_files:
                    opend_files.write(log_string + '
    ')
                return func(*args, **kwargs)
            return wrapped_functions
        return logging_decorator
    
    
    @logit
    def myfunc1():
        pass
    

      示例三

    def outer_arg(bar):
        def outer(func):
            def inner(*args, **kwargs):
                ret = func(*args, **kwargs)
                print(bar)
                return ret
            return inner
        return outer
    
    # 相当于 outer_arg('foo_arg')(foo)()
    
    
    @outer_arg('foo_arg')
    def foo(a, b, c):
        return (a+b+c)
    
    
    print(foo(1,3,5))
    

      示例四

    class Count(object):
        def __init__(self, func):
            self._func = func
            self.num_calls = 0
    
        def __call__(self, *args, **kwargs):  # 模拟成函数,将类模拟成可调用的对象
            self.num_calls += 1
            print(f'num of call is {self.num_calls}')
    
    
    @Count
    def example():
        print('hello')
    

      示例五

    def decorator(aClass):
        class newClass(object):
            def __init__(self, args):
                self.times = 0
                self.wrapped = aClass(args)
    
            def display(self):
                # 将runtime()替换为display()
                self.times += 1
                print('run times ', self.times)
                self.wrapped.display()
    
        return newClass
    
    @decorator
    class MyClass(object):
        def __init__(self, number):
            self.number = number
    
        # 重写display
        def display(self):
            print('number is', self.number)
    
    
    six = MyClass(6)
    for i in range(5):
        six.display()
    

      

  • 相关阅读:
    Java I/O的典型使用方式
    搜索--hiho 骑士问题
    编程之美--水王(找出出现超过1/2的数)
    深入理解java虚拟机之类文件结构以及加载
    【转载】Java JVM 运行机制及基本原理
    整数的划分总结(转)
    java静态方法和非静态方法
    mongodb 运行错误总结
    MongoDb windows环境安装,附百度云链接
    JAVA解析Json数据
  • 原文地址:https://www.cnblogs.com/workherd/p/14401916.html
Copyright © 2020-2023  润新知