python decorator
简单记录一下python修饰符@
的理解和使用方法,一直没好好理解,现在卡住了。。。参考wiki的定义, A decorator is any callable Python object that is used to modify a function, method or class defination. The decorator syntax is pure syntactic sugar, using @
as the keyword.即python修饰符作为一种python对象,用来修饰函数、方法或者类。
参考Wiki,我们简单实现一个修饰符的样例,
|
|
在ipython环境下执行,有如下结果,
所以,修饰符的用途,等价于如下情形,
最直观的理解就是decorator简化了calculator()
中的部分代码。正如wiki中的解释:Decorators are a form of metaprogramming; they enhance the action of the function or method they decorate.
这篇博客还分析了修饰符嵌套的执行顺序问题,感兴趣可以参考一下。
References
[1] Python syntax and semantics#Decorators
[2] Python修饰符 (一)—— 函数修饰符 “@”