装饰器

装饰器
定义:本质是函数,装饰其他函数,就是为其他函数添加附加功能。
原则:1.不能修改被装饰函数的源代码
2.不能修改被装饰函数的调用方式
知识储备:
1.函数即“变量”
2.高阶函数:
a.把一个函数名以实参的形式传给另一个函数(在不修改被修饰函数源代码的情况下为其添加新功能)
b.返回值中包含函数名(不修改函数夫人调用方式)
3.嵌套函数:在函数中定义一个函数
装饰器实例;
 1 #Task:给test添加一个计时函数
 2 import time
 3 def timer(func):
 4     def deco():
 5         start_time = time.time()
 6         func()
 7         stop_time = time.time()
 8         print('the func time is %s '%(stop_time - start_time))
 9     return deco
10 @timer  #test = timer(test)这就是所谓语法糖
11 def test():
12     time.sleep(3)
13     print('in the test')
14 test()

Output:

in the test
the func time is 3.0004241466522217 

 带参数的装饰器:

这段代码将验证方式分为两种,一种local,一种ldap,此段只实现local逻辑,ldap以print函数带过。

 1 username, passwd = "sugar", "abc"
 2 def auth(auth_type):
 3     print("auth_func", auth_type )
 4     def outer_wrapper(func):
 5         def wrapper(*args, **kwargs):
 6             print("wrapper func args:",*args, **kwargs)
 7             if auth_type == "local":
 8                 user = input("Please input username:")
 9                 password = input("Please input passwd:")
10                 if user == username and password == passwd:
11                     print("\033[32;1msuccessful pass\033[0m")
12                     res = func(*args, **kwargs)
13                     print("------afterauth----")
14                     return res
15                 else:
16                     exit("\033[31;1mInvalid username or password\033[0m")
17             elif auth_type == "ldap":
18                 print(input("名场面:我信你个鬼,你个糟老头子,坏的很。。。"))
19         return wrapper
20     return outer_wrapper
21 
22 def index():
23     print("welcome to index page")
24 
25 @auth(auth_type = "local")#先给装饰器传参数,再将home函数名作为参数传给outerwrapper(),
26 def home():
27     print("welcome to home page")
28     return "from home"
29 
30 @auth(auth_type = "ldap")
31 def care():
32     print("welcome to care page")
33 
34 index()
35 print(home())
36 care()

 








posted @ 2019-01-23 09:28  椰汁软糖  阅读(115)  评论(0编辑  收藏  举报