【笔记】如何为被装饰的函数保存元数据

在函数对象中保存着一些函数的元数据,例如:

  f.__name__    :  函数的名字

  f.__doc__       :  函数文档字符串

  f.__moudle__  :  函数所属模块名

  f.__dict__    : 属性字典

  f.__defaults__  : 默认参数元组

使用装饰器后,再使用上面这些属性访问时,看到的是内部包裹函数的元数据,原来的元数据便丢掉了。

解决方案:使用标准库functools中的装饰器wraps装饰内部包裹函数,可以定制将原函数的某些属性,更新到包裹函数上面

 1 # coding:utf8
 2 from functools import wraps
 3 def mydecorator(func):
 4     @wraps(func)
 5     def wrapper(*args,**kargs):
 6         '''wrapper function'''
 7         print 'In wrapper'
 8         func(*args,**kargs)
 9     return wrapper
10 
11 @mydecorator    
12 def example():
13     '''example function'''
14     print 'In example'
15     
16     
17 print example.__name__
18 print example.__doc__
原文地址:https://www.cnblogs.com/banshaohuan/p/6932996.html