定义:
  
本质是函数,功能是“装饰”其它函数,即为其他函数添加附加功能
原则:
1、不能修改被装饰函数的源代码;
2、不能修改被装饰函数的调用方式
实现装饰器知识储备:
1、函数即“变量”;
2、高阶函数;
3、嵌套函数。

实例1:初始版
# 定义装饰器函数
import time
def qt_fun(func):
def gj_func(*args,**kwargs): #关键点,定义不定实参传入值个数*args,形参个数**kwargs
start_time=time.time()
func(*args,**kwargs) #关键点,传入参数
stop_time=time.time()
print('运行时间:',stop_time-start_time)
return gj_func #关键点,返回值。 @qt_fun #关键点,引用装饰器,相当于:test1 = qt_fun(test1)
def test1(name):
time.sleep(1)
print('姓名:',name) @qt_fun #关键点,引用装饰器,test2 = qt_fun(test2) test2()
def test2(name,age,addrs):
time.sleep(2)
print('姓名:%s 年龄:%s 地址:%s'%(name,age,addrs)) #test1 = qt_fun(test1)
#test1() #可替换成 @qt_fun @装饰器名 #调用函数
test1('simple')
test2('simple',26,'四川')


实例2:终极版

user_name = 'simple'
password = '123'
def choose_type(c_type):
def login_f(func):
def in_fun(*args,**kwargs):
if c_type == 'A':
print('当前选择的验证方式为:', c_type)
name=input('用户名:').strip()
passwd=input('密码:').strip()
if name==user_name and passwd==password:
print('登录成功!')
func(*args,**kwargs)
else:
exit('用户名或密码不正确,登录失败!')
elif c_type == 'B':
print('当前选择的验证方式为:', c_type)
print('此验证方式,开发中....')
else:
print('输入的验证方式不正确!')
return in_fun
return login_f @choose_type(c_type=input('请选择home的验证方式(A/B):').strip())
def home():
print('欢迎进入主页!') @choose_type(c_type=input('请选择bbs的验证方式(A/B):').strip())
def bbs():
print('欢迎进入bbs界面!') def index():
print('欢迎光临index界面!此界面无需验证!') home()
bbs()
index()

输出结果:

最新文章

  1. 编辑器sublime text3和插件package control、Sidebar Enhancements插件安装
  2. 【Java基础】方法
  3. Mybatis在xml文件中处理大于号小于号的方法
  4. 51nod1537 分解
  5. HDOJ/HDU 2535 Vote(排序、)
  6. Visual Prolog 的 Web 专家系统 (6)
  7. file_get_contents无法请求https连接的解决方法
  8. Qt Creator编译运行成功,但是显示系统找不到指定的文件(比如urlmon.dll动态链接库)
  9. ConstraintLayout知识记录
  10. Vue+Webpack构建移动端京东金融(一、开发前准备)
  11. Django积木块五——分页
  12. Xadmin添加,编辑,删除
  13. laravel中的登录页面逻辑
  14. datagrid行内编辑时为datetimebox
  15. Codeforces Round #258 (Div. 2) C. Predict Outcome of the Game 水题
  16. LeetCode--191--位1的个数
  17. Docker Compose 部署前后端分离应用
  18. Lingo 做线性规划 - Marketing Applications
  19. FORALL用法小结
  20. 修改 Cloud image 的密码的简单方法

热门文章

  1. 【Java 基础】Java动态代理
  2. 使用$.ajax方式实现页面异步访问,局部更新的效果
  3. 【C/C++】二维数组的传参的方法/二维字符数组的声明,使用,输入,传参
  4. Redis单点到集群迁移
  5. String类源码分析
  6. Winamp栈溢出漏洞研究
  7. 预算(Project)
  8. CF979A Pizza, Pizza, Pizza!!! 题解
  9. Redis缓存穿透、击穿、雪崩,数据库与缓存一致性
  10. 贪心——122.买卖股票的最佳时机II