本文主要介绍Python编程语言中常见的修饰器函数及修饰器类的用法。
问题
方法
无参修饰器函数
def aop(foo):
def wrapper():
print('before')
foo()
print('after')
return wrapper
@aop # 修饰器函数
def say_hello():
print('hello')
if __name__ == '__main__':
say_hello()
有参修饰器函数
from functools import wraps
def aop(foo):
@wraps(foo) #! 提供参数
def wrapper(*args, **kwargs): #!
print('before')
foo(*args, **kwargs) #! 容易出错
print('after')
return wrapper
@aop # 修饰器函数
def say_hello(name):
print('hello', name)
if __name__ == '__main__':
say_hello(name = 'chen')
修饰器类
from functools import wraps
class AOP:
def __call__(self, foo):
@wraps(foo)
def wrapper(*args, **kwargs):
print('before')
foo(*args, **kwargs)
print('after')
return wrapper #! 容易出错
@AOP() #! 注意是实例化对象
def say_hello(name):
print('hello', name)
if __name__ == '__main__':
'''
Exception has occurred: TypeError
'NoneType' object is not callable
'''
say_hello(name='chen')
结语