1. 程式人生 > >Python-裝飾器-示例

Python-裝飾器-示例

%s odin index war ret flag pri pyc timeout


#!/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()












Python-裝飾器-示例