python之decorator理解
2012-03-05 19:27
267 查看
The only constraint on the result of a decorator is that it be callable, so it can
properly replace the decorated function.
decorator唯一限制是它必须是callable的,所以如果class作为decorator必须实现__call__方法使其成为callable的对象,而函数本身就是callable的。
用class做decorator
输出:
如何解释这个输出,关键在于decorator程序的阅读要从程序执行顺序来理解,把decorator当成一次函数调用。
当程序从上至下执行到第7行时,my_decorator开始初始化,它以aFunction作为参数,传入__init__()执行,然后__call__将原函数替换,执行第10行代码,最后调用aFunction,因为这时原函数调用时,调用的是decorator替换后的callable对象,也就是__call__方法,所以执行的实际上是__call__。
函数作为decorator
同样,程序执行到第8行,调用entry_exit将func1当参数传入执行,返回new_f替换原函数,对func2同样处理,最后调用func1和func2时实际上调用的就是替换了以后的函数。
所以decorator从根本上是函数指针的替换,用一个callable的对象替换原来的函数。
properly replace the decorated function.
decorator唯一限制是它必须是callable的,所以如果class作为decorator必须实现__call__方法使其成为callable的对象,而函数本身就是callable的。
用class做decorator
class my_decorator(object): def __init__(self, f): print("inside my_decorator.__init__()") f() # Prove that function definition has completed def __call__(self): print("inside my_decorator.__call__()") @my_decorator def aFunction(): print("inside aFunction()") print("Finished decorating aFunction()") aFunction()
输出:
inside my_decorator.__init__() inside aFunction() Finished decorating aFunction() inside my_decorator.__call__()
如何解释这个输出,关键在于decorator程序的阅读要从程序执行顺序来理解,把decorator当成一次函数调用。
当程序从上至下执行到第7行时,my_decorator开始初始化,它以aFunction作为参数,传入__init__()执行,然后__call__将原函数替换,执行第10行代码,最后调用aFunction,因为这时原函数调用时,调用的是decorator替换后的callable对象,也就是__call__方法,所以执行的实际上是__call__。
函数作为decorator
def entry_exit(f): def new_f(): print("Entering", f.__name__) f() print("Exited", f.__name__) return new_f @entry_exit def func1(): print("inside func1()") @entry_exit def func2(): print("inside func2()") func1() func2()
同样,程序执行到第8行,调用entry_exit将func1当参数传入执行,返回new_f替换原函数,对func2同样处理,最后调用func1和func2时实际上调用的就是替换了以后的函数。
所以decorator从根本上是函数指针的替换,用一个callable的对象替换原来的函数。
相关文章推荐
- 对于python中的self,cls,decorator的理解
- 对于python中的self,cls,decorator的理解
- 装饰器学习(2)------深入理解Python 装饰器(decorator)
- python self,cls,decorator的理解
- 对Python中装饰器(Decorator)的理解与进阶
- python self,cls,decorator的理解
- python decorator的理解
- 深入理解Python 装饰器(decorator)
- 对于python中的self,cls,decorator的理解
- 深入理解Python 装饰器(decorator)
- 深入理解python装饰器和闭包
- Python字符编码学习理解
- [置顶] 建议53:用状态模式美化代码,关于python-state工具包的理解
- Python Decorator 和函数式编程
- 理解python中yield关键字
- Python编写带参数decorator
- 【Python爬虫实战--1】深入理解urllib;urllib2;requests
- python要先好好理解
- 机器学习之深入理解神经网络理论基础、BP算法及其Python实现
- Python:生成器的简单理解