021--python装饰器
一、装饰器含义
装饰器本质就是函数,为其它函数添加附加功能
二、装饰器原则
1.不修改被修饰函数的代码
2.不修改被修饰函数的调用方式
三、装饰器知识
装饰器 = 高阶函数 + 函数嵌套 + 闭包
四、装饰器介绍
1.装饰器基本框架
def timer(func): #func为被修饰函数
def wrapper(): #函数嵌套
func() #执行func函数
return wrapper
2、基本装饰器(基本框架+参数+功能+返回值+使用装饰器+语法糖@)
import time def timmer(func): #func=test
def wrapper():
# print(func)
start_time=time.time()
func() #就是在运行test()
stop_time = time.time()
print('运行时间是%s' %(stop_time-start_time))
return wrapper @timmer #test=timmer(test) timmer执行后会返回wrapper地址赋值给test
def test():
time.sleep(3)
print('test函数运行完毕') test()
3.加上返回值的装饰器
import time def timmer(func): #func=test
def wrapper():
# print(func)
start_time=time.time()
res = func() #就是在运行test()
stop_time = time.time()
print('运行时间是%s' %(stop_time-start_time))
return res
return wrapper @timmer #test=timmer(test) timmer执行后会返回wrapper地址赋值给test
def test():
time.sleep(3)
print('test函数运行完毕')
return '这是test的返回值' res2 = test()
print (res2) 输出:
test函数运行完毕
运行时间是3.0001718997955322
这是test的返回值
4.加上参数的装饰器
import time
def timmer(func): #func=test1
def wrapper(*args,**kwargs): #test('linhaifeng',age=18) args=('linhaifeng') kwargs={'age':18}
start_time=time.time()
res=func(*args,**kwargs) #就是在运行test() func(*('linhaifeng'),**{'age':18})
stop_time = time.time()
print('运行时间是%s' %(stop_time-start_time))
return res
return wrapper # @timmer #test=timmer(test)
def test(name,age):
time.sleep(3)
print('test函数运行完毕,名字是【%s】 年龄是【%s】' %(name,age))
return '这是test的返回值' @timmer
def test1(name,age,gender):
time.sleep(1)
print('test1函数运行完毕,名字是【%s】 年龄是【%s】 性别【%s】' %(name,age,gender))
return '这是test的返回值' # res=test('linhaifeng',age=18) #就是在运行wrapper
# # print(res)
# test1('alex',18,'male') test1('alex',18,'male')
5.带参数的装饰器
1 user_list=[
2 {'name':'alex','passwd':''},
3 {'name':'linhaifeng','passwd':''},
4 {'name':'wupeiqi','passwd':''},
5 {'name':'yuanhao','passwd':''},
6 ]
7 current_dic={'username':None,'login':False}
8
9 def auth(auth_type='filedb'):
10 def auth_func(func):
11 def wrapper(*args,**kwargs):
12 print('认证类型是',auth_type)
13 if auth_type == 'filedb':
14 if current_dic['username'] and current_dic['login']:
15 res = func(*args, **kwargs)
16 return res
17 username=input('用户名:').strip()
18 passwd=input('密码:').strip()
19 for user_dic in user_list:
20 if username == user_dic['name'] and passwd == user_dic['passwd']:
21 current_dic['username']=username
22 current_dic['login']=True
23 res = func(*args, **kwargs)
24 return res
25 else:
26 print('用户名或者密码错误')
27 elif auth_type == 'ldap':
28 print('鬼才特么会玩')
29 res = func(*args, **kwargs)
30 return res
31 else:
32 print('鬼才知道你用的什么认证方式')
33 res = func(*args, **kwargs)
34 return res
35
36 return wrapper
37 return auth_func
38
39 @auth(auth_type='filedb') #auth_func=auth(auth_type='filedb')-->@auth_func 附加了一个auth_type --->index=auth_func(index)
40 def index():
41 print('欢迎来到京东主页')
42
43 @auth(auth_type='ldap')
44 def home(name):
45 print('欢迎回家%s' %name)
46 #
47 @auth(auth_type='sssssss')
48 def shopping_car(name):
49 print('%s的购物车里有[%s,%s,%s]' %(name,'奶茶','妹妹','娃娃'))
50
51 # print('before-->',current_dic)
52 # index()
53 # print('after--->',current_dic)
54 # home('产品经理')
55 shopping_car('产品经理')
def auth(n):
def myfunc(func):
def wrapper(*args,**kwargs):
if n=='':
return func(*args,**kwargs)
else:
print('can shu bu cun zai')
return wrapper
return myfunc
@auth('')
def index():
print('欢迎来到京东主页') index()
支持参数的装饰器
021--python装饰器的更多相关文章
- 关于python装饰器
关于python装饰器,不是系统的介绍,只是说一下某些问题 1 首先了解变量作用于非常重要 2 其次要了解闭包 def logger(func): def inner(*args, **kwargs) ...
- python装饰器通俗易懂的解释!
1.python装饰器 刚刚接触python的装饰器,简直懵逼了,直接不懂什么意思啊有木有,自己都忘了走了多少遍Debug,查了多少遍资料,猜有点点开始明白了.总结了一下解释得比较好的,通俗易懂的来说 ...
- Python 装饰器学习
Python装饰器学习(九步入门) 这是在Python学习小组上介绍的内容,现学现卖.多练习是好的学习方式. 第一步:最简单的函数,准备附加额外功能 1 2 3 4 5 6 7 8 # -*- c ...
- python 装饰器修改调整函数参数
简单记录一下利用python装饰器来调整函数的方法.现在有个需求:参数line范围为1-16,要求把9-16的范围转化为1-8,即9对应1,10对应2,...,16对应8. 下面是例子: def fo ...
- python 装饰器学习(decorator)
最近看到有个装饰器的例子,没看懂, #!/usr/bin/python class decorator(object): def __init__(self,f): print "initi ...
- Python装饰器详解
python中的装饰器是一个用得非常多的东西,我们可以把一些特定的方法.通用的方法写成一个个装饰器,这就为调用这些方法提供一个非常大的便利,如此提高我们代码的可读性以及简洁性,以及可扩展性. 在学习p ...
- 关于python装饰器(Decorators)最底层理解的一句话
一个decorator只是一个带有一个函数作为参数并返回一个替换函数的闭包. http://www.xxx.com/html/2016/pythonhexinbiancheng_0718/1044.h ...
- Python装饰器由浅入深
装饰器的功能在很多语言中都有,名字也不尽相同,其实它体现的是一种设计模式,强调的是开放封闭原则,更多的用于后期功能升级而不是编写新的代码.装饰器不光能装饰函数,也能装饰其他的对象,比如类,但通常,我们 ...
- Python装饰器与面向切面编程
今天来讨论一下装饰器.装饰器是一个很著名的设计模式,经常被用于有切面需求的场景,较为经典的有插入日志.性能测试.事务处理等.装饰器是解决这类问题的绝佳设计,有了装饰器,我们就可以抽离出大量函数中与函数 ...
- python装饰器方法
前几天向几位新同事介绍项目,被问起了@login_required的实现,我说这是django框架提供的装饰器方法,验证用户是否登录,只要这样用就行了,因为自己不熟,并没有做过多解释. 今天查看dja ...
随机推荐
- 解决asp.net core 日期格式 datetime Json返回 带T的问题
原文:解决asp.net core 日期格式 datetime Json返回 带T的问题 记录一下: Startup中,将 services.AddMvc(); 改为: services.AddMvc ...
- pycharm、idea插件代理设置,插件安装
pycharm和idea都是intellij的,所以插件安装是设置代理方法相似, 以pycharm举例: 1.已经安装的插件列表: 2.查找要安装的插件,没有,会给出下载插件的链接地址: 3.打开链接 ...
- [WASM] Create a New Rust/Webpack Project using the rust-webpack Template
Previous to this post, we set up our own Rust/wasm project from scratch. The Rust/wasm team ships a ...
- 生活娱乐 Wifi机器人的制作流程
思路简单,但是创意无限~~ 动手能力超强 牛人教你做Wifi机器人(图) 一.前言 Wifi机器人(Wifi Robot):其实是一辆能通过互联网,或500米以外的笔记本无线设施来远程控制的遥控汽车. ...
- SolidEdge如何绘制阵列之后取消掉某一些
在最后一步点击"抑制事件",然后可以在被阵列的圆形上单击,被抑制的圆形变成灰色
- weex stream 方法封装
1.封装 api.js // 配置API接口地址 const baseUrl = 'http://www.kuitao8.com/'; // 引入 弹窗组件 var modal = weex.requ ...
- HDU 3305 Ice-sugar Gourd
Ice-sugar Gourd Time Limit: 5000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)T ...
- hibernate的查询缓存和二级缓存的配合使用
我的上一篇博客Hibernate缓存体系之查询缓存(query cache),以及list和iterate方法的差别介绍了查询缓存的概念,以及list和iterate的差别.读者可能注意到:那篇博客測 ...
- No Memory Alignment with GCC
attribute method: #include <stdio.h> struct packed { char a; int b; } __attribute__((packed)); ...
- linux led子系统(一)
就像学编程第一个范例helloworld一样,学嵌入式,单片机.fpga之类的第一个范例就是点亮一盏灯.对于庞大的linux系统,当然可以编写一个字符设备驱动来实现我们需要的led灯,也可以直接利用g ...