Open jzztf opened 6 years ago
参考: http://blog.csdn.net/hqzxsc2006/article/details/50337865
当定义装饰器时, 相当于将原函数换成了另一个, 会缺失其本身的"name","docstring"和其他一些信息. functools的"@wraps"本身也是装饰器传递了原函数的信息
def star(func): def add_star(*args,**kargs): print("*"*30) func(*args,**kargs) print("*"*30) return add_star
@star def printer(msg): """printer docstring""" print(msg)
printer("hello world") print(printer.name) print(printer.doc)
- 输出: ```bash ****************************** hello world ****************************** add_star None
from functools import wraps
def star(func): @wraps(func) def add_star(*args,*kargs): print(""30) func(args,*kargs) print(""*30) return add_star
- 输出: ```bash ****************************** hello world ****************************** printer printer docstring
functools模块中的wraps方法
参考: http://blog.csdn.net/hqzxsc2006/article/details/50337865
不加@wraps的修饰器
@star def printer(msg): """printer docstring""" print(msg)
printer("hello world") print(printer.name) print(printer.doc)
添加@wraps后
def star(func): @wraps(func) def add_star(*args,*kargs): print(""30) func(args,*kargs) print(""*30) return add_star
@star def printer(msg): """printer docstring""" print(msg)
printer("hello world") print(printer.name) print(printer.doc)