.P.S.
func_name 相当于 __name__
__doc__函数的字符串文档
__module__函数处于哪个模块
__defaults__保留函数的默认参数,在python,默认函数在创建函数时就定义好了。记住,不是调用时创建哦
__closure__ 访问函数的闭包
在默认参数中最好不要使用可变对象。
def mydecorator(func):
def wrapper(*args,**kargs):
'''wrapper function'''
prtin('In wrapper')
func(*args,**kargs)
return wrapper
@mydecorator
def example():
'''example function'''
print('In example')
print(example.__name__)
print(example.__doc__)
在这段代码中,我们可以example函数的元数据被覆盖掉了
我们可以这样解决,但是这也太不爽了吧
def mydecorator(func):
def wrapper(*args,**kargs):
'''wrapper function'''
prtin('In wrapper')
func(*args,**kargs)
wrapper.__name__ = func.__name__
return wrapper
@mydecorator
def example():
'''example function'''
print('In example')
print(example.__name__)
print(example.__doc__)
from functools import update_wrapper,wraps,WRAPPER_ASSIGNMENTS,WRAPPER_UPDATES
def mydecorator(func):
#第一种方法: wraps是一个便捷函数
@wraps(func,('__name__','__doc__'),('__dict__',))
def wrapper(*args,**kargs):
'''wrapper function'''
print('In wrapper')
func(*args,**kargs)
# wrapper.__name__ = func.__name__
# update_wrapper(包袱函数,被操作函数,元组,被操作函数属性添加到包袱函数的对象)
# 元组:指明用被操作函数的哪些属性直接替换包袱函数的对象
#第二种方法: update_wrapper(wrapper,func,('__name__','__doc__'),('__dict__',))
return wrapper
@mydecorator
def example():
'''example function'''
print('In example')
print(example.__name__)
print(example.__doc__)
print(WRAPPER_ASSIGNMENTS) #默认第三参数
print(WRAPPER_UPDATES) #默认第四参数