装饰器,是Python中较为独特的语法糖之一。以下是官方文档定义:
A function returning another function, usually applied as a function transformation using the @wrapper syntax. Common examples for decorators are classmethod() and staticmethod().
The decorator syntax is merely syntactic sugar, the following two function definitions are semantically equivalent:
def f(...):
...
f = staticmethod(f)
@staticmethod
def f(...):
...
The same concept exists for classes, but is less commonly used there. See the documentation for function definitions and class definitions for more about decorators.
英语渣渣尬翻:
大意:一个函数返回在另一个函数中,通常使用 @wrapper
来实现函数的转换。
装饰器语法仅仅是语法糖,例子中的两个函数在语义上是等价的。
之前见到一个例子很贴切足以解释装饰器:计算一个函数的运行时间。
不用装饰器的人会这样写
import time
def func1(func):
startTime = time.time()
func()
endTime = time.time()
secr = (endTime - startTime) * 1000
print('spend %f' %(secr))
def func():
print("hello")
if __name__ == '__main__':
func1(func)
每次监测时间的时候就会将被检测的函数作为检测函数的参数
用装饰器的人会这么写
import time
def deco(func):
def wrapper():
startTime = time.time()
func()
endTime = time.time()
secr = (endTime - startTime) * 1000
print('spend %f' %(secr))
return wrapper
@deco
def func():
print("hello")
if __name__ == '__main__':
func()
那么之后定义需要监测时间的函数的时候,只需要在前面加上@deco
即可,简单便捷,不是吗?
最后还需要说明两点:装饰器是可叠加使用的,还有装饰器可以加参数