python之装饰器

对已定义的函数,可以在函数运行期间动态的增加功能称为“装饰器”,不改变该函数既有逻辑功能;

def log(func):
    def wrapper(*args,**kwargs):
        print('This is {} run'.format(func.__name__))
        return func(*args,**kwargs)
    return wrapper

@log
def say_hello():
    print('hello,this is a test_demo')

if __name__ =='__main__':

  r = say_hello()
结果输出:
This is say_hello run hello,this is a test_demo

上面例子中,log函数既为一个装饰器,say_hello()函数通过@log的方式调用装饰器,把自己作为一个变量参数传递给log()函数,log函数中又嵌套了一个wrapper函数,wrapper函数传参为*args,**kwargs即可传任意参数,该函数主要功能为在执行被作为参数传进来的func函数前现执行 print('This is {} run'.format(func.__name__))语句,执行完毕后再执行参数函数func( )

当然装饰器本身也可以传入参数

def log(text):
    def decorator(func):
        def wrapper(*args,**kwargs):
            print('{} and {}() is runnig now'.format(text,func.__name__))
            return func(*args,**kwargs)
        return wrapper
    return decorator


@log('this text is denpend your input')
def say_hello():
    print('hello,this is a test_demo')


if __name__ =='__main__':
    r = say_hello()
运行结果:
this text is denpend your input and say_hello() is runnig now hello,this is a test_demo

上面的log函数中传入一个'this text is denpend your input'字符串作为入参,在log函数中通过嵌套多层函数来实现装饰器自定义入参

上一篇:JPEG版本


下一篇:JavaScript中var与let,const的区别