【转】九步学习python装饰器
本篇日志来自:http://www.cnblogs.com/rhcad/archive/2011/12/21/2295507.html 纯转,只字未改。只是为了学习一下装饰器。其实现在也是没有太看明白,对于装饰器我就是用的时候找例子,能蒙对,但是用过之后一段时间就忘了。还是用的少。有空应该好好看一看的,包括闭包。对于各种现代编程语言来说闭包都是很重要的。在这里先谢过原作者,如有侵权请告知。
=-=-=-=-=-=-=-=-=-=-一条不怎么华丽的分隔线-=-=-=-=-=-=-=-=-=-=
这是在Python学习小组上介绍的内容,现学现卖、多练习是好的学习方式。
第一步:最简单的函数,准备附加额外功能
# -*- coding:gbk -*-
'''示例1: 最简单的函数,表示调用了两次''' def myfunc():
print("myfunc() called.") myfunc()
myfunc()
第二步:使用装饰函数在函数执行前和执行后分别附加额外功能
# -*- coding:gbk -*-
'''示例2: 替换函数(装饰)
装饰函数的参数是被装饰的函数对象,返回原函数对象
装饰的实质语句: myfunc = deco(myfunc)''' def deco(func):
print("before myfunc() called.")
func()
print(" after myfunc() called.")
return func def myfunc():
print(" myfunc() called.") myfunc = deco(myfunc) myfunc()
myfunc()
第三步:使用语法糖@来装饰函数
# -*- coding:gbk -*-
'''示例3: 使用语法糖@来装饰函数,相当于“myfunc = deco(myfunc)”
但发现新函数只在第一次被调用,且原函数多调用了一次''' def deco(func):
print("before myfunc() called.")
func()
print(" after myfunc() called.")
return func @deco
def myfunc():
print(" myfunc() called.") myfunc()
myfunc()
第四步:使用内嵌包装函数来确保每次新函数都被调用
# -*- coding:gbk -*-
'''示例4: 使用内嵌包装函数来确保每次新函数都被调用,
内嵌包装函数的形参和返回值与原函数相同,装饰函数返回内嵌包装函数对象''' def deco(func):
def _deco():
print("before myfunc() called.")
func()
print(" after myfunc() called.")
# 不需要返回func,实际上应返回原函数的返回值
return _deco @deco
def myfunc():
print(" myfunc() called.")
return 'ok' myfunc()
myfunc()
第五步:对带参数的函数进行装饰
# -*- coding:gbk -*-
'''示例5: 对带参数的函数进行装饰,
内嵌包装函数的形参和返回值与原函数相同,装饰函数返回内嵌包装函数对象''' def deco(func):
def _deco(a, b):
print("before myfunc() called.")
ret = func(a, b)
print(" after myfunc() called. result: %s" % ret)
return ret
return _deco @deco
def myfunc(a, b):
print(" myfunc(%s,%s) called." % (a, b))
return a + b myfunc(1, 2)
myfunc(3, 4)
第六步:对参数数量不确定的函数进行装饰
# -*- coding:gbk -*-
'''示例6: 对参数数量不确定的函数进行装饰,
参数用(*args, **kwargs),自动适应变参和命名参数''' def deco(func):
def _deco(*args, **kwargs):
print("before %s called." % func.__name__)
ret = func(*args, **kwargs)
print(" after %s called. result: %s" % (func.__name__, ret))
return ret
return _deco @deco
def myfunc(a, b):
print(" myfunc(%s,%s) called." % (a, b))
return a+b @deco
def myfunc2(a, b, c):
print(" myfunc2(%s,%s,%s) called." % (a, b, c))
return a+b+c myfunc(1, 2)
myfunc(3, 4)
myfunc2(1, 2, 3)
myfunc2(3, 4, 5)
第七步:让装饰器带参数
# -*- coding:gbk -*-
'''示例7: 在示例4的基础上,让装饰器带参数,
和上一示例相比在外层多了一层包装。
装饰函数名实际上应更有意义些''' def deco(arg):
def _deco(func):
def __deco():
print("before %s called [%s]." % (func.__name__, arg))
func()
print(" after %s called [%s]." % (func.__name__, arg))
return __deco
return _deco @deco("mymodule")
def myfunc():
print(" myfunc() called.") @deco("module2")
def myfunc2():
print(" myfunc2() called.") myfunc()
myfunc2()
第八步:让装饰器带 类 参数
# -*- coding:gbk -*-
'''示例8: 装饰器带类参数''' class locker:
def __init__(self):
print("locker.__init__() should be not called.") @staticmethod
def acquire():
print("locker.acquire() called.(这是静态方法)") @staticmethod
def release():
print(" locker.release() called.(不需要对象实例)") def deco(cls):
'''cls 必须实现acquire和release静态方法'''
def _deco(func):
def __deco():
print("before %s called [%s]." % (func.__name__, cls))
cls.acquire()
try:
return func()
finally:
cls.release()
return __deco
return _deco @deco(locker)
def myfunc():
print(" myfunc() called.") myfunc()
myfunc()
第九步:装饰器带类参数,并分拆公共类到其他py文件中,同时演示了对一个函数应用多个装饰器
# -*- coding:gbk -*-
'''示例9: 装饰器带类参数,并分拆公共类到其他py文件中
同时演示了对一个函数应用多个装饰器''' from mylocker import * class example:
@lockhelper(mylocker)
def myfunc(self):
print(" myfunc() called.") @lockhelper(mylocker)
@lockhelper(lockerex)
def myfunc2(self, a, b):
print(" myfunc2() called.")
return a + b if __name__=="__main__":
a = example()
a.myfunc()
print(a.myfunc())
print(a.myfunc2(1, 2))
print(a.myfunc2(3, 4))
下面是参考资料,当初有不少地方没看明白,真正练习后才明白些:
1. Python装饰器学习 http://blog.csdn.net/thy38/article/details/4471421
2. Python装饰器与面向切面编程 http://www.cnblogs.com/huxi/archive/2011/03/01/1967600.html
3. Python装饰器的理解 http://apps.hi.baidu.com/share/detail/17572338
【转】九步学习python装饰器的更多相关文章
- http://python.jobbole.com/85056/ 简单 12 步理解 Python 装饰器,https://www.cnblogs.com/deeper/p/7482958.html另一篇文章
好吧,我标题党了.作为 Python 教师,我发现理解装饰器是学生们从接触后就一直纠结的问题.那是因为装饰器确实难以理解!想弄明白装饰器,需要理解一些函数式编程概念,并且要对Python中函数定义和函 ...
- python 装饰器 (个人理解就是前置的内建函数)
感谢有篇文件详细介绍[简单 12 步理解 Python 装饰器]http://python.jobbole.com/85056/ 1.首先介绍内建函数 2.转换为装饰器 3.执行顺序 4.装饰器实用
- 遥想大肠包小肠----python装饰器乱弹
说起装饰器就tm蛋疼,在老男孩学习python装饰器,结果第二天默写,全错了,一道题抄十遍,共计二十遍. 要是装饰器是一人,我非要约他在必图拳馆来一场...... 下面容我展示一下默写二十遍的成果 语 ...
- Python装饰器学习(九步入门)
这是在Python学习小组上介绍的内容,现学现卖.多练习是好的学习方式. 第一步:最简单的函数,准备附加额外功能 ? 1 2 3 4 5 6 7 8 # -*- coding:gbk -*- '''示 ...
- Python入门之装饰器九步学习入门
第一步:最简单的函数,准备附加额外功能 '''示例1: 最简单的函数,表示调用了两次''' def myfunc(): print("myfunc() called.") myfu ...
- Python 装饰器学习
Python装饰器学习(九步入门) 这是在Python学习小组上介绍的内容,现学现卖.多练习是好的学习方式. 第一步:最简单的函数,准备附加额外功能 1 2 3 4 5 6 7 8 # -*- c ...
- Python装饰器学习
Python装饰器学习(九步入门) 这是在Python学习小组上介绍的内容,现学现卖.多练习是好的学习方式. 第一步:最简单的函数,准备附加额外功能 ? 1 2 3 4 5 6 7 8 # -*- ...
- (转载)Python装饰器学习
转载出处:http://www.cnblogs.com/rhcad/archive/2011/12/21/2295507.html 这是在Python学习小组上介绍的内容,现学现卖.多练习是好的学习方 ...
- Python高级特性: 12步轻松搞定Python装饰器
12步轻松搞定Python装饰器 通过 Python 装饰器实现DRY(不重复代码)原则: http://python.jobbole.com/84151/ 基本上一开始很难搞定python的装 ...
随机推荐
- Bash编程(5) Shell方法
shell的方法在相同的进程内执行,与调用它的脚本一致.对于方法来说,脚本中的所有变量均可见,且不需要执行export.方法中可以创建局部变量,且不影响正在调用的脚本. 1. 定义语法 (1) Kor ...
- AtCoder Grand Contest 006 F - Blackout
Description 在 \(n*n\) 的棋盘上给出 \(m\) 个黑点,若 \((x,y)\),\((y,z)\) 都是黑点,那么 \((z,x)\) 也会变成黑点,求最后黑点的数量 题面 So ...
- 【Hadoop系列】linux SSH原理解析
本文中斜体加粗代表shell指令,操作环境 CentOS6.5 linux root免密码登录链接:[Hadoop系列]linux下 root用户免密码登录远程主机 ssh. linux 非root用 ...
- mysql主从复制测试
mysql主从复制测试: 1. 配置主服务器:在主库上面添加复制账号GRANT REPLICATION SLAVE on *.* to 'mark'@'%' identified by 'mark' ...
- Rabbit简单队列模式
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/ ...
- 简单的CRUD(一)
一.JDBC的概述--(来源于百度) JDBC(Java DataBase Connectivity,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问, ...
- Java温故而知新(5)设计模式详解(23种)
一.设计模式的理解 刚开始“不懂”为什么要把很简单的东西搞得那么复杂.后来随着软件开发经验的增加才开始明白我所看到的“复杂”恰恰就是设计模式的精髓所在,我所理解的“简单”就是一把钥匙开一把锁的模式,目 ...
- 设计模式入门,单件模式,c++代码实现
// test05.cpp : Defines the entry point for the console application.// #include "stdafx.h" ...
- hdu 4055 Number String(递推DP)
给一个只含‘I','D','?'三种字符的字符串,I表示当前数字大于前面的数字,D表示当前的数字小于前面一位的数字,?表示当前位既可以小于又可以大于. 问1~n的排列中有多少个满足该字符串. http ...
- java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.yunweather.app.db.YunWeatherDB.loadProvinces()' on a null object reference
NullPointerException:查看自己的什么地方是否对空指针进行了操作 Attempt to invoke virtual method 'java.util.List com.yunwe ...