这个比较复杂
def before(func): #定义装饰器 def wrapper(*args, **kwargs): print('Before function called.') return func(*args, **kwargs) return wrapper def after(func): #定义修装饰器 def wrapper(*args, **kwargs): result = func(*args, **kwargs) print('After function called.') return result return wrapper @before @after def test(*args,**kwargs): #同时使用两个装饰器装饰函数 print(args) test(123) # 调用被装饰的函数 print(test(123))
多个装饰器装饰一个函数
# 带参数的装饰器:(相当于开关)为了给装饰器传参 F = True # 为True时就加上装饰器 # F = False # 为False时就去掉装饰器 def outer(flag): def wrapper(func): def inner(*args, **kwargs): if flag: print('before') ret = func(*args, **kwargs) print('after') else: ret = func(*args, **kwargs) return ret return inner return wrapper @outer(F) # outer(F) = wrapper -> @wrapper -> f1 = wrapper(f1) def f1(): print('in f1') @outer(False) # outer(F) = wrapper -> @wrapper -> f2 = wrapper(f2) def f2(): print('in f2') f1() f2() print(f1())
import time def door(func): def wapper(): start_time=time.time() func() time.sleep(3) stop_time=time.time() print(abs(start_time-stop_time)) return wapper @door def test1(): print('in the test1:') test1()
简单的装饰器 test1=door(test1)
import time def foo(func): def wapper(*args,**kwargs): print(args,end='') func(*args) print(kwargs) return wapper @foo #test=foo(test) def test(*args): print('in test 1:',args) test(123,456,s='袁珂')
带参函数