decorator接受一个函数,然后添加一些功能,最后返回这个函数。在这篇文章中,你会知道如何创建decorator以及为什么要用这个语法。
1. What are decorators in Python?
python有个有意思的特性叫decorator,在现存代码中添加某些功能。这叫做meta-programming,试图在编译时修改另一部分程序。
2. Prerequisites for learning decorators
为了理解decorator,我们首先弄清楚Python中的一些基础。我们一定要接受Python的观点,一切皆对象。意味着我们只要定义与这些对象相关的identifier就行。其中函数也不例外,他们也是对象。不同的名字可以绑定相同的函数对象。
def first(msg):
print(msg)
first("Hello")
second = first
second("Hello")
你在跑代码的时候,first 和second给出了相同的输出,在这,first和second都引用相同的函数对象。
下面看看更奇怪的事情。
函数作为参数传递到另外一个函数中。
如果你用过诸如map,filter,reduce这样的函数,你就这道什么意思了。
把函数作为参数的函数我们叫higher order functions。下面给出个例子:
def inc(x):
return x + 1
def dec(x):
return x - 1
def operate(func, x):
result = func(x)
return result
#运行结果如下:
>>> operate(inc,3)
4
>>> operate(dec,3)
2
而且,函数也能返回另一个函数
def is_called():
def is_returned():
print