python装饰器要点:
1. 装饰器能够给被装饰的函数在不改变调用方式的情况下,增加功能,如日志,计时等等
2. 被装饰函数包含有不带参数的,带参数的
3. 装饰器本身也分为不带参数和带参数的
1 import time 2 def deco(func): 3 def wraper(*args): 4 start_time = time.time() 5 func(*args) 6 stop_time = time.time() 7 print("running time is:",stop_time - start_time) 8 return wraper 9 10 @deco #等于test1 = deco(test1) 返回值为wraper的内存地址,即test1等于wraper,所有*args同样可以传递给wraper 11 def test1(*args): 12 print("test1".center(30,"-")) 13 print("values is",*args) 14 test1(1,2,3) 15 16 17 user = "jack" 18 def auth(auth_type): 19 def outer_wraper(func): 20 def wraper(*args,**kwargs): 21 if auth_type=="local": 22 username = input("username:").strip() 23 if user == username: 24 print("success!") 25 res = func() 26 return res 27 else: 28 print("invalid input") 29 return wraper 30 return outer_wraper 31 32 @auth(auth_type="local") #即这里多了一个参数,这个参数需要传递给auth函数,多了这个参数可以再装饰器内加判断 33 def home(): 34 print("home page") 35 36 home()
扩展阅读
http://blog.csdn.net/thy38/article/details/4471421