Python装饰器7-解决装饰器语法糖问题

Python publisher01 42℃

示例代码

#! -*- 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的原理不再分析。

转载请注明:Python量化投资 » Python装饰器7-解决装饰器语法糖问题

喜欢 (0)or分享 (0)