Python装饰器7-解决装饰器语法糖问题
2019-06-15 本文已影响0人
dnsir
示例代码
#! -*- coding: utf-8 -*-
from functools import wraps
"""
解决装饰器存在的语法问题
"""
def a_new_decorator(a_func):
# 带参数的装饰器->next section would know more about
@wraps(a_func)
def wrapTheFunction():
print("I am doing some boring work before a_func()")
a_func()
print("im am doing some boring work after a_func()")
return wrapTheFunction
@a_new_decorator
def a_function_requiring_decoration():
print("I am the function which need some decoration to remove my foul smell")
a_function_requiring_decoration()
print(a_function_requiring_decoration.__name__)
执行结果:
I am doing some boring work before a_func()
I am the function which need some decoration to remove my foul smell
im am doing some boring work after a_func()
# __name__属性正确了
a_function_requiring_decoration
小结
通过from functools import wraps
可以解决装饰器语法改变函数属性name的问题,wraps
的原理不再分析。