使⽤装饰器时,有⼀些细节需要被注意。
例如,被装饰后的函数其实已经是另外⼀个函数了(函数名等函数属性会发⽣改变)。添加后由于函数名和函数的doc发⽣了改变,对测试结果有一定影响!
import functools
def itcast1(fun):
# 带参数的装饰器
#wraps是用来将inner函数的属性设置为fun的属性值
@functools.wraps(fun)
def inner(*args, **kwargs):
print("itcast1 start")
fun(*args, **kwargs)
print("itcast1 end")
return inner
也可以用这种方法来表示:
# def itcast1(fun):
#
# definner(*args, **kwargs):
# print("itcast1 start")
# fun(*args, **kwargs)
# print("itcast1 end")
#
# inner.__name__ = fun.__name__
# inner.__doc__ = fun.__doc__
#
#
# returninner
@itcast1
def say_hello():
"""itcast funsay_hello"""
print("hello")
print(say_hello.__name__) # inner.__name__
print(say_hello.__doc__)