为实现软件开发中的 “封闭——开放” 原则,在修改函数时应做到:已实现的功能代码块不做出修改,对现有功能进行扩展开发。
1.定义一个函数,实现操作为:两个数 x,y 相加,相加完后系统停顿 5s
import time
def add(x,y):
print(x+y)
time.sleep(5)
add(5,9)
>>>
14
Process finished with exit code 0
2.对此函数加以修饰,使得:输出x,y 相加之前的时间值,输出 x,y 相加之后的时间值。
import time
def show_time(f):
def innr(x,y):
print(time.time())
f(x,y)
print(time.time())
return innr
#此时 @show_time 为装饰器
@show_time
def add(x,y):
print(x+y)
time.sleep(5)
add(5,9)
>>>
1537437504.234399
14
1537437509.246096
import time
def longger(flag):
def show_time(f):
def inner(*x,**y):
start=time.time()
f(*x,**y)
end=time.time()
if flag==True:
print(end-start)
return inner
return show_time
@longger(True)
def add(*x,**y):
num=0
for i in x:
num+=i
print(num)
time.sleep(5)
add(1,2,3,4,5,6)
>>>
21
5.008791923522949