python 装饰器使用总结
python 装饰器使用总结
by:授客 QQ:1033553122
测试环境
win10
python 3.5
例1:一个简单的例子
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'shouke'
def wrapper_method1(func):# func用于接收被装饰的函数地址
def wrapper():
print("执行wrapper_method1")
func()#调用被装饰的函数
return wrapper#返回方法地址,供执行被装饰函数前调用
@wrapper_method1#等同于wrapper_method1(myfunction)
def myfuntion():
print("执行myfunction")
myfuntion()
运行结果:
执行wrapper_method1
执行myfunction
例2:装饰带参数函数
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'shouke'
def wrapper_method1(func):
def wrapper(name, age):#这里的参数列表和myfuntion参数列表保持一致
print("执行wrapper_method1 name:%s age:%s" % (name, age))
func(name, age)#记得给要调用的函数传递参数
return wrapper
@wrapper_method1
def myfuntion(name, age):
print("执行myfunction name:%s age:%s" % (name, age))
myfuntion('shouke', 'unknow')
运行结果:
执行wrapper_method1 name:shouke age:unknow
执行myfunction name:shouke age:unknow
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'shouke'
def wrapper_method1(func):
def wrapper(*args, **kwargs):
print("执行wrapper_method1 args:", args)
func(*args, **kwargs)
return wrapper
@wrapper_method1
def myfuntion(*args,**kwargs):
print("执行myfunction args:", args)
myfuntion('shouke', 'unknow')
运行结果:
执行wrapper_method1 args: ('shouke', 'unknow')
执行myfunction args: ('shouke', 'unknow')
例3:函数被多给装饰器方法装饰
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'shouke'
def wrapper_method1(func):
def wrapper(*args, **kwargs):
print("执行wrapper_method1")
func(*args, **kwargs)
return wrapper
def wrapper_method2(func):
def wrapper():
print("执行wrapper_method2")
func()
return wrapper
@wrapper_method1
@wrapper_method2
def myfuntion():
print("执行myfunction")
myfuntion()
运行结果:
执行wrapper_method1
执行wrapper_method2
执行myfunction
说明:装饰器方法执行顺序为从远到近,从上到下。
例4:在类中使用装饰器
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'shouke'
def wrapper_method1(func):
def wrapper(*args, **kwargs):
print("执行wrapper_method1")
func(*args, **kwargs)
return wrapper
class MyClass:
def __init__(self):
pass
@staticmethod
@wrapper_method1
def myfuntion():
print("执行myfunction")
MyClass.myfuntion()
运行结果:
执行wrapper_method1
执行myfunction
例5:装饰器方法也可以是类函数
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'shouke'
class MyClass2:
@staticmethod
def wrapper_method1(func):
def wrapper(*args, **kwargs):
print("执行wrapper_method1")
func(*args, **kwargs)
return wrapper
class MyClass:
def __init__(self):
pass
@staticmethod
@MyClass2.wrapper_method1
def myfuntion():
print("执行myfunction")
MyClass.myfuntion()
运行结果:
执行wrapper_method1
执行myfunction
需要注意的点
1、 即便被装饰函数拥有默认值也要显示传递参数,否则报错,如下:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'shouke'
def wrapper_method1(func):
def wrapper(name, age):
print("执行wrapper_method1 name:%s age:%s" % (name, age))
func(name, age)
return wrapper
@wrapper_method1
def myfuntion(name='shouke', age='unknow'):
print("执行myfunction name:%s age:%s" % (name, age))
myfuntion()
运行结果:
TypeError: wrapper() missing 2 required positional arguments: 'name' and 'age'
2、 如果被装饰函数为类的静态函数时,@staticmethod必须位于最上方,否则报错,如下:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'shouke'
def wrapper_method1(func):
def wrapper(*args, **kwargs):
print("执行wrapper_method1")
func(*args, **kwargs)
return wrapper
class MyClass:
def __init__(self):
pass
@wrapper_method1
@staticmethod
def myfuntion():
print("执行myfunction")
MyClass.myfuntion()
运行结果:
Traceback (most recent call last):
执行wrapper_method1
File "E:/PrivateReops/CassTestManage/TMP/backend/mytest.py", line 34, in <module>
MyClass.myfuntion()
File "E:/PrivateReops/CassTestManage/TMP/backend/mytest.py", line 9, in wrapper
func(*args, **kwargs)
TypeError: 'staticmethod' object is not callable
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 ...
随机推荐
- Modelarts与无感识别技术生态总结(浅出版)
[摘要] Modelarts技术及相关产业已成为未来AI与大数据重点发展行业模式之一,为了促进人工智能领域科学技术快速发展,modelarts现状及生态前景成为研究热点.笔者首先总结modelarts ...
- NIO-Channel
目录 NIO-Channel 目录 前言 什么是Channel 通道类型 如何使用 ServerSocketChannel SocketChannel FileChannel 总结 相关文献 NIO- ...
- KETTLE多表关联的同步一张表的两种实现方式
以下操作都在5.0.1版本下进行开发,其余版本可以进行自动比对 在平时工作当中,会遇到这种情况,而且很常见.比如:读取对方的多个视图或者表,写入目标库的一张表中,就涉及到多表的同步. 多表同步可以有以 ...
- luogu P2507 [SCOI2008]配对
题目描述 你有 n 个整数Ai和n 个整数Bi.你需要把它们配对,即每个Ai恰好对应一个Bp[i].要求所有配对的整数差的绝对值之和尽量小,但不允许两个相同的数配对.例如A={5,6,8},B={5, ...
- mac 安装 XX-Net-3.12.11
目录 一 下载xx-net稳定版 二 使用Chrome浏览器 三 开启IPv6 mac禁用SIP机制 SIP 步骤 其他 附完整的csrutil命令 一 下载xx-net稳定版 github稳定版-X ...
- 数据库Oracle字符处理函数
练习字符处理函数(数据库表都是从1开始),我们用到一张"伪表" dual: dual 表:dual 是一张只有一个字段,一行记录的表.dual 表也称之为'伪表',因为他不存储主题 ...
- ARTS-S 在docker中运行本地脚本
很多情况是本地没有编译环境,但docker中有编译环境.想编译本地代码,就要把本地的代码和编译脚本映射到docker中,脚本如下: docker run \ -it \ -v /Users/usern ...
- 深入学习 Arduino LinkedList库(一个变长的集合类数组)
QQ技术互动交流群:ESP8266&32 物联网开发 群号622368884,不喜勿喷 单片机菜鸟博哥CSDN 1.前言 博主是做Android App开发出身的,所以对Java这门语言算是有 ...
- Django 10
目录 cookie和session cookie session token Django中间件 自定义中间件 process_request process_response 其他方法 cookie ...
- Python3 类与对象之王者荣耀对战小游戏
王者荣耀对战小游戏 # 定义英雄: 亚瑟 class Arthur: hero_type = 'Tank' def __init__(self, attack_value=164, armor=98, ...