装饰器:本质上是一个Python函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外功能,装饰器的返回值也是一个函数对象。
def debug(func):
def wrapper():
print ("[DEBUG]: enter {}()".format(func.__name__))
return func()
return wrapper
def say_hello():
print ("hello!")
say_hello = debug(say_hello) # 添加功能并保持原函数名不变
say_hello()
def funA(func):
print('funA_out')
def wrapper(*args, **kwargs):
print('funA')
return func(*args, **kwargs)
return wrapper
def funB(func):
print('funB_out')
def wrapper(*args, **kwargs):
print('funB')
return func(*args, **kwargs)
return wrapper
@funA
@funB
def funC():
print('funC')
print('------------------------')
funC()
输出:
funB_out
funA_out
------------------------
funA
funB
funC
解析@后的内容,直接就把@下一行的函数或者类作为@后边的函数的参数,然后将返回值赋值给下一行修饰的函数对象。
注:@就是需要运行生成性函数:def funC()为funA(funB(funC)),因为它需要运行生成新的funC,所以会打印出funB_out,funA_out。但是,funA,funB里面的wrapper是def其是不会运行的。wrapper里面的功能会传递给funC,所以需要拓展funC的功能就需要将拓展的功能放在wrapper里面。
参考:python @的作用 - CSDN博客blog.csdn.net详解Python的装饰器 - Toby Qin - 博客园www.cnblogs.com
欢迎关注公众号:huangxiaobai880