示例代碼
#! -*- coding: utf-8 -*-
from functools import wraps
"""
解決裝飾器存在的語法問題
"""
def a_new_decorator(a_func):
# 帶參數(shù)的裝飾器->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__)
執(zhí)行結(jié)果:
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
小結(jié)
通過from functools import wraps
可以解決裝飾器語法改變函數(shù)屬性name的問題汉嗽,wraps
的原理不再分析篙耗。