代码如下:
author = 'damao'
import time
"""
python是用于拓展原来函数功能的一种函数;特殊之处在于它的返回值是一个函数,
使用装饰器的好处:不用更改原来函数的代码前提下给函数增加新的功能
"""
class TestOne(object):
# 原始函数
def test_func(self):
print("holle")
time.sleep(1)
print("world")
class TestTwo(object):
"""使用原始方法修改函数内容,达到修改需求的目的"""
def test_func(self):
start_time = time.time() # 获取当前时间
print("holle")
time.sleep(1)
print("world")
end_time = time.time() # 获取结束时间
sec = (end_time - start_time)/1000
print("运行的总时间是:{a}".format(a=sec))
class TestThere(object):
"""避免直接侵入原函数修改,但是生效需要再次执行函数"""
def test_func(self):
print("holle")
time.sleep(1)
print("world")
def sum_time(self):
start_time = time.time() # 获取当前时间
self.test_func()
end_time = time.time() # 获取结束时间
sec = (end_time - start_time) / 1000
print("运行的总时间是:{a}".format(a=sec))
"""装饰器简单模型"""
def sum_time(test_func):
def wrapper():
start_time = time.time() # 获取当前时间
test_func()
end_time = time.time() # 获取结束时间
sec = (end_time - start_time) / 1000
print("运行的总时间是:{a}".format(a=sec))
return wrapper
@sum_time
def test_func():
print("holle")
time.sleep(1)
print("world")
"""带有参数的装饰器"""
def sum_time1(test_func1):
def wrapper(a,b):
start_time = time.time() # 获取当前时间
test_func1(a,b)
end_time = time.time() # 获取结束时间
sec = (end_time - start_time) / 1000
print("运行的总时间是:{a}".format(a=sec))
return wrapper
@sum_time1
def test_func1(a,b):
print("二个数之和是:",a+b)
return a + b
"""不定参数的装饰器"""
def sum_time2(func):
def wrapper(*args,**kwargs):
start_time = time.time() # 获取当前时间
func(*args,**kwargs)
end_time = time.time() # 获取结束时间
sec = (end_time - start_time) / 1000
print("运行的总时间是:{a}".format(a=sec))
return wrapper
@sum_time2
def test_func2(a,b):
print("二个数之和是:",a+b)
return a + b
@sum_time2
def test_func3(a,b,c):
print("几个数之和是:",a + b + c)
return a + b + c
"""多个装饰器"""
def sum_01(func):
def wrapper(*args,**kwargs):
start_time = time.time() # 获取当前时间
func(*args,**kwargs)
end_time = time.time() # 获取结束时间
sec = (end_time - start_time) / 1000
print("运行的总时间是:{a}".format(a=sec))
return wrapper
def sum_02(func):
def wrapper(*args,**kwargs):
a = func(*args,**kwargs)
b = a * 100
print(b)
return wrapper
@sum_01
@sum_02
def aaa(a,b):
print("二个数之和是:",a+b)
return a + b
if __name__=="__main__":
aaa(12,12)
网友评论