python装饰器的学习笔记

此博文是我对装饰器的一些理解,如果有错误欢迎及时留言,我会第一时间向大家学习。

一、什么是装饰器

1、从字面意义来看:

是用来给函数装饰打扮的函数

 

2、理论上可以理解为:

(1)、不改变函数的运行方式

(2)、不改变函数体内容的情况下给函数添加新的功能

 

3、装饰器的结构:

装饰器=高阶函数+函数嵌套+闭包

 

二、装饰器的种类

下面就利用两个例子来实现一下带参装饰器和不带参装饰器使用。

1、不带参数的装饰器

 1 user ={'name':'test','passwd':'123'}
 2 
 3 user_status = {'name':None,'login':False}
 4 
 5 def auth_func(func):
 6     def warper(*args,**kwargs):
 7         if user_status['name'] and user_status['login']:
 8             res = func(*args,**kwargs)
 9             return res
10         name = input("username: ")
11         passwd = input("password: ")
12         if user['name'] == name and user['passwd'] == passwd:
13             user_status['name'] = name
14             user_status['login'] = True
15             res = func(*args,**kwargs)
16             return res
17         else:
18             print("用户名或密码错误")
19     return warper
20 
21 @auth_func
22 def index(name):
23     print("欢迎%s 来到主页" % name)
24 
25 @auth_func
26 def home(name):
27     print("我在home下")
28 
29 index("test")
30 home('test')
31 
32 #输出
33 username: test
34 password: 123
35 欢迎test 来到主页
36 我在home下

 

2、带参数的装饰器

 1 auth_user_dict ={'username':None,'password':False}
 2 
 3 def load_fileBD():
 4     with open("userDB",'r') as f:
 5         return f.read()
 6 
 7 
 8 def auth(auth_type = 'file'):
 9     def auth_func(func):
10         def wraper(*args,**kwargs):
11             if auth_type == 'file':
12                 fild_data = load_fileBD()
13                 fild_data = eval(fild_data)
14                 if auth_user_dict['username'] and auth_user_dict['password']:
15                     res = func(*args,**kwargs)
16                     return res
17                 username = input('username: ')
18                 passwd = input('password: ')
19                 for user_info in fild_data:
20                     if username == user_info['username'] and passwd == user_info['password']:
21                         auth_user_dict['username'] = username
22                         auth_user_dict['password'] = passwd
23                         res = func(*args,**kwargs)
24                         return res
25                 else:
26                     print("用户名密码错误")
27             elif auth_type == 'mysql':
28                 print("从mysql中读取用户并验证,以print代表执行验证")
29                 res = func(*args,**kwargs)
30                 return res
31             else:
32                 print("没有这种类型的数据库")
33         return wraper
34     return auth_func
35 
36 @auth('mysql')
37 def home(name):
38     print("%s is login in home" % name)
39 
40 home('test')
41 
42 #输出
43 从mysql中读取用户并验证,以print代表执行验证
44 test is login in home

 

posted on 2017-04-17 10:10  小强灰灰  阅读(194)  评论(0编辑  收藏  举报

导航