Python一个很好玩的特性decorator
2013-12-24 13:27
106 查看
直接上代码,这个例子是从《The Quick Python Book 2ed》里面抄出来的,代码是Python3的。
不用decorator的代码
输出如下
使用decorator的代码
输出如下
没有实际项目中使用过,但是,这应该是一个很有用的特性。原函数myfunction打印参数下标0的元素,但是使用decorator的函数,即用dec123修饰的函数myfunction不止运行了原函数本身,还运行了原函数之前和之后的一些“修饰”代码。如果对myfunction的运行结果有怀疑的话,可以用decorator来debug,打印myfunction运行之前的运行状况和myfunction运行之后的运行状况,甚至可以用另一个函数替换myfunction。例如
将myfunction改为调用print,输出如下
这样的写法似乎太邪恶了,如果纯粹出于debug的目的也就算了,改完记得把代码还原......
不用decorator的代码
def myfunction(parameter): print(parameter[0]) myfunction("hello")
输出如下
h
使用decorator的代码
def dec123(func): print("in decorate function, decorating", func.__name__) def wrapper_func(*args): print("Executing", func.__name__) return func(*args) return wrapper_func @dec123 def myfunction(parameter): print(parameter[0]) myfunction("hello")
输出如下
in decorate function, decorating myfunction Executing myfunction h
没有实际项目中使用过,但是,这应该是一个很有用的特性。原函数myfunction打印参数下标0的元素,但是使用decorator的函数,即用dec123修饰的函数myfunction不止运行了原函数本身,还运行了原函数之前和之后的一些“修饰”代码。如果对myfunction的运行结果有怀疑的话,可以用decorator来debug,打印myfunction运行之前的运行状况和myfunction运行之后的运行状况,甚至可以用另一个函数替换myfunction。例如
def dec123(func): print("in decorate function, decorating", func.__name__) def wrapper_func(*args): print("Executing", func.__name__) return print(*args) return wrapper_func @dec123 def myfunction(parameter): print(parameter[0]) myfunction("hello")
将myfunction改为调用print,输出如下
in decorate function, decorating myfunction Executing myfunction hello
这样的写法似乎太邪恶了,如果纯粹出于debug的目的也就算了,改完记得把代码还原......
相关文章推荐
- 用 Python 的 Descriptor 特性解决一个变态的问题
- 用 Python 的 Descriptor 特性解决一个变态的问题
- 用 Python 的 Descriptor 特性解决一个变态的问题
- 用 Python 的 Descriptor 特性解决一个变态的问题
- python 试题:请描述decorator(装饰器)的用法和它的应用场景,如果可以的话,写一个decorator
- 问题的原因是“SSL: CERTIFICATE_VERIFY_FAILED”。 Python 升级到 2.7.9 之后引入了一个新特性,当使用urllib.urlopen打开一个 https 链接时,
- python 之用装饰器@property,把方法变成一个特性
- 用python设计的一个小游戏
- python写的一个squid访问日志分析的小程序
- python打包列表文件到一个包
- python写的一个服务器自动巡检工具
- 每天一个python段子(1):xpath
- python写的一个omniORB的调用用例
- Python:尝试写一个简单的类
- 一个完整的python程序
- 使用Python语言高效地处理一个文本文件
- 一个简单的python(tornado + sqlalchemy)web小例子
- Python源码学习十一 一个常用的内存分配函数
- Python3基础 描述符类与自制property方法 __get__,__set__,__delete__方法 讲一个特殊的类的实例指派给另一个类的属性
- 可爱的 Python: Decorator 简化元编程