什么是装饰器?
- 在不改变原来代码的基础上,修改代码的逻辑
- 本质就是一个高阶函数
- 语法糖是@
- 分类
- 函数装饰器:定义一个函数当做装饰器
- 类装饰器:定义一个类当做装饰器
- 装饰器可以修饰普通方法,类方法,类...
- 装饰器可以叠加使用
函数装饰器
def decorator(func):
def _decorator(*args, **kwargs):
print('decorator called, start!')
ret = func(*args, **kwargs)
print('decorator called, end!')
return ret
return _decorator
@decorator
def test(data):
print('test : %s' % data)
test('ok')
def decorator(*args, **kwargs):
print(args[0])
print(kwargs['one'])
def _decorator(func):
def __decorator(*args, **kwargs):
print('decorator called, start!')
ret = func(*args, **kwargs)
print('decorator called, end!')
return ret
return __decorator
return _decorator
@decorator('x', one = 'a')
def test(data):
print('test : %s' % data)
test('ok')
类装饰器
class decorator:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print('decorator called, start!')
ret = self.func(*args, **kwargs)
print('decorator called, end!')
return ret
@decorator
def test(data):
print('test : %s' % data)
test('ok')
class decorator:
def __init__(self, x):
self.x = x
def __call__(self, func):
print(self.x)
def _dectorator(*args, **kwargs):
print('decorator called, start!')
ret = func(*args, **kwargs)
print('decorator called, end!')
return ret
return _dectorator
@decorator('a')
def test(data):
print('test : %s' % data)
test('ok')