value success star invalid user wrap net ces
python 装饰器要点:
1. 装饰器能够给被装饰的函数在不改变调用方式的情况下,增加功能,如日志,计时等等
2. 被装饰函数包含有不带参数的,带参数的
3. 装饰器本身也分为不带参数和带参数的
- 1 import time
- 2 def deco(func):
- 3 defwraper(*args):
- 4start_time = time.time()
- 5func(*args)
- 6stop_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 deftest1(*args):
- 12 print("test1".center(30,"-"))
- 13 print("values is",*args)
- 14test1(1,2,3)
- 15
- 16
- 17user ="jack"
- 18 def auth(auth_type):
- 19 def outer_wraper(func):
- 20 defwraper(*args,**kwargs):
- 21 ifauth_type=="local":
- 22username = input("username:").strip()
- 23 ifuser == username:
- 24 print("success!")
- 25res = 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
- 36home()
扩展阅读
http://blog.csdn.net/thy38/article/details/4471421
python--- 装饰器
来源: http://www.bubuko.com/infodetail-2145148.html