装饰器-示例
Posted 安东尼漂流记
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了装饰器-示例相关的知识,希望对你有一定的参考价值。
!/usr/bin/env python
-- coding: utf-8 --
@Time : 2018/6/3 0003 11:47
@Author : Anthony.Waa
@Site :
@File : test.py
@Software: PyCharm
示例1:
带状态的装饰器
from functools import wraps
import time
def timeout(flag1):
def timmer(f):
‘‘‘
此函数用于显示被装饰函数的运行效率,打印运行市场即为正确
:param f: f = JD()
:return:
‘‘‘
@wraps(f)
def inner(*args,**kwargs):
if flag1:
start_time = time.time()
ret = f(*args,**kwargs)
end_time = time.time()
print(‘此函数的执行效率%s‘ % (end_time - start_time))
return ret
else:
ret = f(*args, **kwargs)
return ret
return inner
return timmer
flag = False
@timeout(flag)
def JD():
‘‘‘
此处为被装饰函数
:return:
‘‘‘
time.sleep(0.3)
print(‘非常复杂......‘)
return 666
JD()
示例2
带参数的装饰器
from functools import wraps
import time
def timeout(flag1):
def timmer(f):
‘‘‘
此函数用于显示被装饰函数的运行效率,打印运行市场即为正确
:param f: f = JD()
:return:
‘‘‘
@wraps(f)
def inner(*args,**kwargs):
if flag1:
start_time = time.time()
ret = f(*args,**kwargs)
end_time = time.time()
print(‘此函数的执行效率%s‘ % (end_time - start_time))
return ret
else:
ret = f(*args, **kwargs)
return ret
return inner
return timmer
@timeout(‘京东‘)
def JD():
‘‘‘
此处为被装饰函数
:return:
‘‘‘
time.sleep(0.3)
print(‘我是京东......‘)
return 666
@timeout(‘淘宝‘)
def taobao():
‘‘‘
此处为被装饰函数
:return:
‘‘‘
time.sleep(0.3)
print(‘我是淘宝......‘)
return 666
JD()
taobao()
示例3:
多个装饰器装饰一个函数
import time
def wrapper1(func1): # func = inner2
def inner1():
print(‘wrapper1 ,before func‘) # 1
func1() # inner2
print(‘wrapper1 ,after func‘) # 7
return inner1
def wrapper2(func2): # func2 = inner3
def inner2():
print(‘wrapper2 ,before func‘) # 2
func2() # inner3
print(‘wrapper2 ,after func‘) # 6
return inner2
def wrapper3(func3): # func3 = index()
def inner3():
print(‘wrapper3 ,before func‘) # 3
func3() # index()
print(‘wrapper3 ,after func‘) # 5
return inner3
@wrapper1 # index = wrapper1(inner2)
@wrapper2 # index = wrapper2(inner3)
@wrapper3 # index = wrapper3(index)
def index():
print(‘in my heart‘) # 4
time.sleep(0.3)
index()
以上是关于装饰器-示例的主要内容,如果未能解决你的问题,请参考以下文章