Python装饰器的进阶

时间:2024-05-18 22:06:02

带参数的装饰器

示例一:Python自带的装饰器函数

from functools import wraps
import time
def Time(func1):
@wraps(func1)
def Wrapper(*args,**kwargs):
start = time.time()
ret = func1(args)
end = time.time()
print(end - start)
return ret
return Wrapper def func1(day):
time.sleep(0.5)
'''好嗨呦'''
print('放假%s天'%day)
return '好开心' func1 = Time(func1)
ret = func1(10)
print(func1.__name__)
# 打印函数的名字
print(func1.__doc__)
# 打印函数中注释部分内容;不过我用的python 3.5 ,__doc__这个内置函数好像并未生效,老男孩的代码也没有生效,下次注意研究

示例二:装饰器带参数的使用(三层嵌套)

import time
Conditions = True
# 在已经写好的装饰器中要对装饰器做参数判断,可以使用三层嵌套来完成,在嵌套外部定义一个判断值;这样就不用改动后续代码,只需要改动判断值即可;
def Time_out(Conditions):
def Time(func1):
def inner(*args,**kwargs):
if Conditions:
start = time.time()
ret = func1(*args,**kwargs)
end = time.time()
print(end - start)
return ret
else:
ret = func1(*args,**kwargs)
return ret
return inner
return Time
Time = Time_out(Conditions) @Time
def fun1():
time.sleep(0.5)
print('func1') @Time
def fun2():
print('func2')
time.sleep(0.5)
fun1()
fun2()

多个装饰器装饰一个函数

def wrapper1(func):
def inner1():
print('wrapper1 ,before func')
ret = func()
print('wrapper1 ,after func')
return ret
return inner1 def wrapper2(func):
def inner2():
print('wrapper2 ,before func')
ret = func()
print('wrapper2 ,after func')
return ret
return inner2 def wrapper3(func):
def inner3():
print('wrapper3 ,before func')
ret = func()
print('wrapper3 ,after func')
return ret
return inner3 @wrapper3
@wrapper2
@wrapper1
def f():
print('in f')
return '哈哈哈' print(f())

注意事项

  • @装饰器名称,装饰器名称会被当成执行内容先执行,'@装饰器'这个东西要查分成两部分看
  • 一定要记住装饰器的在执行过程中的先后顺序