【15】python之装饰器

1、概念

装饰器本质是函数,作用是装饰其他函数,为其他函数添加附加功能

原则:

1.不能修改被装饰的函数的源代码
2.不能修改被装饰的函数的调用方式

实现装饰器需要知道:

1.函数即"变量"--关键
2.高阶函数
a:把一个函数名当做实参传给另外一个函数
b:返回值中包含函数名
3.嵌套函数:函数里面定义函数

2、装饰器的实现

高阶函数+嵌套函数=》装饰器

实现计算函数执行的时间功能

初始代码

1 def bar1():
2     time.sleep(2)
3     print("in the bar1")
4     
5 bar1()

实现功能代码1:改变源代码

 1 # 改变源代码
 2 import time
 3 def bar1():
 4     start_time = time.time()
 5     time.sleep(2)
 6     print("in the bar1")
 7     stop_time = time.time()
 8     print('the func run times is %s' % (stop_time - start_time))
 9 
10 bar1()

实现功能代码2:改变了调用方式

 1 # 改变了调用方式
 2 import time
 3 
 4 def test(func):
 5     start_time = time.time()
 6     func()
 7     stop_time = time.time()
 8     print('the func run times is %s' % (stop_time - start_time))
 9 def bar1():
10     time.sleep(2)
11     print("in the bar1")
12 
13 test(bar1)

实现功能代码3:未改变源代码和调用方式

 1 # 未改变源代码和调用方式
 2 import time
 3 
 4 def timer(func):
 5     def test(*args,**kwargs):
 6         start_time = time.time()
 7         res = func(*args,**kwargs)
 8         return res
 9         stop_time = time.time()
10         print('the func run times is %s' % (stop_time - start_time))
11     return test
12 
13 @timer #bar1 = test(bar1)
14 def bar1():
15     time.sleep(2)
16     print("in the bar1")
17     return "bar1"
18 
19 print(bar1())

 

装饰器样例

 1 user,passwd = "abc","123"
 2 def auth(auth_type):
 3     print("auth",auth_type)
 4     def outer_wrapper(func):
 5         print("outer_wrapper", func)
 6         def wrapper(*args, **kwargs):
 7             print("wrapper",*args, **kwargs)
 8             if auth_type=="local":
 9                 username = input("username:").strip()
10                 password = input("password:").strip()
11                 if user == username and passwd == password:
12                     print("\033[32;1muser has passed authentication\033[0m")
13                     res = func(*args, **kwargs)
14                     return res
15                 else:
16                     exit("\033[31;1minvalid username or password\033[m")
17             else:
18                 print("......")
19         return wrapper
20     return outer_wrapper
21 def index():
22     print("welcome to index page")
23 
24 @auth(auth_type="local") # 加括号执行第一、二层,home=wrapper()
25 def home():
26     print("welcome to home page")
27     return "home"
28 @auth(auth_type="ldap")
29 def bbs(x):
30     print("welcome to bbs page")
31     return x
32 print("index")
33 index()
34 print("home")
35 print(home())
36 print("bbs")
37 bbs(bbs)

 

posted @ 2018-05-16 17:06  才华充电中  阅读(130)  评论(0编辑  收藏  举报