标签:The direct arch containe selection editor z-index space com
import time
def func(): # 定义一个函数
time.sleep(0.01)
print(‘hello world!‘)
def timer(f): # 一个闭包函数,接收一个函数,也叫做装饰器函数
def inner():
start = time.time()
f() # 被装饰函数
end = time.time()
print(end - start)
return inner
func = timer(func)
func()
import time
def timer(f): # 一个闭包函数,接收一个函数,也叫做装饰器函数
def inner():
start = time.time()
f() # 被装饰函数
end = time.time()
print(end - start)
return inner
# 语法糖 @装饰器函数名
def func(): # 被装饰函数 # 定义一个函数 # func = timer(func)
time.sleep(0.01)
print(‘hello world!‘)
# func = timer(func)
func() # 在调用的时候只要调用func()即可!这才是装饰器
import time
def timer(f):
def inner():
start = time.time()
f()
end = time.time()
print(end - start)
return inner
def func():
time.sleep(0.01)
print(‘hello world!‘)
return ‘pontoon on the way!’
ret = func()
print(ret)
>>>hello world!
0.010217905044555664
None # 打印的结果是None,而不是pontoon on the way!,因为这里接收的是inner函数里面的返回值,而inner函数里面并没有返回值
-------------------------------------------------------------------------------------------------------------------------------------------------------
import time
def timer(f):
def inner():
start = time.time()
ret = f() # 得到传递过来函数的返回值
end = time.time()
print(end - start)
return ret # 返回
return inner
def func():
time.sleep(0.01)
print(‘hello world!‘)
return ‘pontoon on the way!‘
# func = timer(func)
ret = func()
print(ret)
>>>hello world!
0.010081291198730469
pontoon on the way!
import time
def timer(f):
def inner(*args, **kwargs):
start = time.time()
ret = f(*args, **kwargs) # 得到传递过来函数的返回值
end = time.time()
print(end - start)
return ret # 返回
return inner
def func(a, b):
time.sleep(0.01)
print(‘hello world!‘)
return ‘pontoon on the way!‘
# func = timer(func)
ret = func(1, 2) # 这里相当于执行inner()
print(ret)
-----------------------------------------------------------------------------------------------
# 简化之
import time
def wrapper(f):
def inner(*args, **kwargs):
ret = f(*args, **kwargs) # 得到传递过来函数的返回值
return ret # 返回
return inner
def func(a, b):
time.sleep(0.01)
print(‘hello world!‘)
return ‘pontoon on the way!‘
# func = timer(func(1, 2))
ret = func(1, 2) # 这里相当于执行inner()
print(ret)
至此简化版的装饰器OK了!
def wrapper(f):
def inner(*args, **kwargs):
ret = f(*args, **kwargs) # 被装饰的函数要有接收的参数并且有返回值!
return ret
return inner
def qqxing():
print(123)
print(qqxing())
标签:The direct arch containe selection editor z-index space com
原文地址:https://www.cnblogs.com/pontoon/p/10238331.html