美文网首页
Python装饰器7-解决装饰器语法糖问题

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

作者: dnsir | 来源:发表于2019-06-15 11:29 被阅读0次

示例代码

#! -*- 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装饰器7-解决装饰器语法糖问题

      本文链接:https://www.haomeiwen.com/subject/nutbfctx.html