一、多装饰器修饰过程
def decorate1(func):
print('decorate1.__init__')
def inner(name):
print('decorate1.pre_func')
func(name)
print('decorate1.after_func')
return inner
def decorate2(func):
print('decorate2.__init__')
def inner(name):
print('decorate2.pre_func')
func(name)
print('decorate2.after_func')
return inner
def decorate3(func):
print('decorate3.__init__')
def inner(name):
print('decorate3.pre_func')
func(name)
print('decorate3.after_func')
return inner
@decorate1
@decorate2
@decorate3
def test_func(name):
print(f'test_func函数被执行了, name={name}')
test_func('zhiyuan')
-
结果:
- 过程分析:
- 初始化过程即: 三个init执行顺序表示python解释器解释代码, 是从右向左, 从里到外
- 初始化过程即: 三个init执行顺序表示python解释器解释代码, 是从右向左, 从里到外
二、带参数的装饰器
- 代码:
from functools import wraps
def log(arg):
def _log(func):
@wraps(func) # 使test1.__name__ = test1, 否则变为 wrapper
def wrapper(*args,**kwargs):
print(f'log开始 ..., arg: {arg}',)
ret = func(*args,**kwargs)
print('log结束 ...')
return ret
return wrapper
return _log
@log('module1')
def test1(s):
print('test1 ..', s)
return s
test1('a')
print(test1.__name__)
-
结果: