import time
def foo():
print("foo.....")
time.sleep(3)
return 1
def soo():
print("soo......")
return 2
def long_time(func):
start_time = time.time()
func()
time.sleep(3)
end_time = time.time()
return print("waesting time %s"%(end_time - start_time))
# f = long_time(foo)
#print(f)
def show_time(func):
def inner():
start_time = time.time()
func()
end_time = time.time()
print("weasting time %s"%(end_time - start_time))
return inner
foo = show_time(foo)#这里是修饰器
foo()
# c = foo#但是我习惯使用佛哦(),现在这么突兀的让我使用foo来调用一个函数,着实不习惯
# print(foo)
# '''这里如何将(end_time - start_time)作为一个返回值传递出来?'''
'''----------------------------------------------------------------------------------------------------------------'''
'''装饰器的另一种高大上的写法'''
def show_time_1(func):
def inner():
start_time = time.time()
func()
end_time = time.time()
print("weasting time %s" % (end_time - start_time))
return
return inner#我知道了。这里的返回值一定是inner而不是inner()。加上括号以后该怎么写??
@show_time_1
def bar1():
print("bar1......")
time.sleep(3)
return 1
bar1()
#关于装饰器这一块的内容我最不理解的就是为什么在最后调用的时候不让我写()???
#装饰器模块
def shwo_times(func):
def inner(*x,**y): #在这里需要传递参数。和原函数需要一个一个进行对应
start_time = time.time()
func(*x,**y)
end_time = time.time()
print("weasting time %s"%(end_time - start_time))
return inner
@shwo_times
#功能函数
def adds(*arge,**arges):
sums = 0
for i in arge:
sums += i
pass
print(sums)
return 1
adds(1,2,3,4,5)
'''另外的一种,要求装饰器含参,带入变量进入运算或者判断
本次是要求在上面的装饰器基础上进行判断。如果传入true字符串,那么就进行打印日志。如果不,则不打印日志'''
time_format = '%Y-%%M-%D %X'
time_current = time.strftime(time_format)
def logger():
with open("日志记录","a") as f :
f.write("%s end_action"%time_current)
#装饰器模块
def when(running = ''):
def shwo_times(func):
def inner(*x,**y): #在这里需要传递参数。和原函数需要一个一个进行对应
start_time = time.time()
func(*x,**y)
end_time = time.time()
print("weasting time %s"%(end_time - start_time))
if running == 'true':
logger()
return inner
return shwo_times
@when('true')
#功能函数
def adds(*arge,**arges):
sums = 0
for i in arge:
sums += i
pass
print(sums)
return 1
adds(1,2,3,4,5)
这个装饰器就很nice了。这里需要注意的就是return的返回值一定是定义函数的名字,不能加上()