首页 > 代码库 > 装饰器

装饰器

 

 

无参装饰器修正(函数参数的对应关系)

 1 import time
 2 
 3 def timmer(func):
 4     def wrapper(name):   #  name与‘pangdi’ 的对应关系
 5         start = time.time()
 6         func(name)       # name
 7         stop = time.time()
 8         print(run time is {}.format(stop-start))
 9     return wrapper
10 
11 @timmer
12 def home(name):
13     time.sleep(1)
14     print(welcome to {} home page.format(name))
15 
16 home(pangdi)  #相当于 wrapper(‘pangdi‘)

 

技术分享
 1 import time
 2 
 3 def timmer(func):
 4     def wrapper(name,password):   #  name,password 与 auth(‘Tom‘,‘123‘) 对应
 5         start = time.time()
 6         func(name,password)       # name
 7         stop = time.time()
 8         print(run time is {}.format(stop-start))
 9     return wrapper
10 
11 
12 @timmer
13 def auth(name,password):
14     print(name,password)
15 
16 auth(Tom,123)
17 
18 #运行结果
19 Tom 123
20 run time is 0.0005013942718505859
简例二(双参数的调用)

 

# *args,**kwargs的特性:面对参数值,有则全收,无则为None

 

技术分享
 1 import time
 2 
 3 def timmer(func):
 4     def wrapper(*args,**kwargs):   #  与 home(‘pangdi‘),auth(‘Tom‘,‘123‘)对应
 5         start = time.time()
 6         func(*args,**kwargs)
 7         stop = time.time()
 8         print(run time is {}.format(stop-start))
 9     return wrapper
10 
11 
12 @timmer
13 def home(name):
14     time.sleep(1)
15     print(welcome to {} home page.format(name))
16 
17 
18 @timmer
19 def auth(name,password):
20     print(name,password)
21 
22 home(pangdi)   #一个参数值
23 print(--*16)
24 auth(Tom,123)  #两个参数
*args,**kwargs  在修正的使用

 

装饰器