简单记录一下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,我们简单实现一个修饰符的样例,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def calculator(f):
print("Begin...")
a = 3.0
b = 2.0
f(a,b)
print("End")
@calculator
def calc_add(a,b):
print("%.2f + %.2f = %.2f" % (a,b,a+b))
@calculator
def calc_minus(a,b):
print("%.2f - %.2f = %.2f" % (a,b,a-b))

在ipython环境下执行,有如下结果,

1
2
3
4
5
6
Begin...
3.00 + 2.00 = 5.00
End
Begin...
3.00 - 2.00 = 1.00
End

所以,修饰符的用途,等价于如下情形,

1
2
3
4
5
6
7
>>> a = 3.0, b = 2.0
>>> print("Begin...")
>>> calc_add(a,b)
>>> print("End")
>>> print("Begin...")
>>> calc_minus(a,b)
>>> print("End")

最直观的理解就是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修饰符 (一)—— 函数修饰符 “@”