Python装饰器(不带参数)
示例
直接给出示例,普通装饰器(即装饰器函数本身不带参数,或参数为实际被包裹的函数):
import time
from functools import wraps
def timethis(func):
'''
Decorator that reports the execution time.
'''
@wraps(func)
def wrapper(*args, **kwargs):
'''
New func
'''
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(func.__name__, end - start)
return result
return wrapper
@timethis
def countdown(n):
'''
Counts down
'''
while n > 0:
n -= 1
装饰器函数接收一个被包裹函数作为参数,然后返回一个新函数作为返回值。
@timethis
def countdown(n):
pass
和下面的写法一样,故装饰器@只是作为一种语法糖。
def countdown(n):
pass
countdown = timethis(countdown)
## 保留被包装函数的元数据 ## 使用@wraps(func)可以保留原始函数的元数据,如下:
>>> countdown.__name__
'countdown'
>>> countdown.__doc__
'\n\tCounts down\n\t'
>>> countdown.__annotations__
{'n': <class 'int'>}
若不使用@wraps(func),结果如下:
>>> countdown.__name__
'wrapper'
>>> countdown.__doc__
'\n\tNew func\n\t'
>>> countdown.__annotations__
{}
## 获取被包装器包裹的原始函数 ## 装饰器已应用于函数,但想“撤消”它,以访问原始的未包装函数。可以按如下方式:
@somedecorator
def add(x, y):
return x + y
orig_add = add.__wrapped__
print(orig_add(3, 4)) # 7
只用再被包裹的函数上使用@wraps才能使用函数的__wrapped__属性。
最后但同样重要的一点是,请注意并非所有装饰器都使用@wraps,因此它们可能无法按所述方式工作。 特别是,内置的装饰器@staticmethod和@classmethod创建的描述符对象不遵循此约定(相反,它们将原始函数存储在__func__属性中)。