| Parameter | Details |
|---|---|
f |
The function to be decorated (wrapped) |
装饰函数是一种软件设计模式。它们可以动态地改变函数、方法或类的功能,而无需直接使用子类或更改装饰函数的源代码。如果使用得当,装饰函数可以成为开发过程中的强大工具。本主题将介绍装饰函数在 Python 中的实现和应用。
Section 37.1: 装饰器功能
装饰器可增强其他函数或方法的行为。任何以函数为参数并返回增强函数的函数都可用作装饰器。
# 这种最简单的装饰器对被装饰的函数没有任何作用。
# 这种最简单的装饰器偶尔可以用作一种代码标记。
def super_secret_function(f):
return f
@super_secret_function
def my_function():
print("This is my secret function.")
@-notation 是语法糖,相当于下面的内容:
my_function = super_secret_function(my_function)
要理解装饰器的工作原理,必须牢记这一点。这种 “未经修饰 ”的语法清楚地说明了为什么装饰器函数需要一个函数作为参数,以及为什么它应该返回另一个函数。它还演示了如果不返回函数会发生什么:
def disabled(f):
"""
This function returns nothing, and hence removes the decorated function
from the local scope.
"""
pass
@disabled
def my_function():
print("This function can no longer be called...")
my_function()
# TypeError: 'NoneType' object is not callable

因此,我们通常会在装饰器中定义一个新函数并返回它。这个新函数首先会做一些它需要做的事情,然后调用原始函数,最后处理返回值。请看这个简单的装饰器函数,它可以打印原始函数接收到的参数,然后调用它。
# This is the decorator
def print_args(func):
def inner_func(*args, **kwargs):
print(args)
print(kwargs)
return func(*args, **kwargs) #Call the original function with its arguments.
return inner_func
@print_args
def multiply(num_a, num_b):
return num_a * num_b
print(multiply(3, 5))
#Output:
# (3,5) - This is actually the 'args' that the function receives.
# {} - This is the 'kwargs', empty because we didn't specify keyword arguments.
# 15 - The result of the function.

Section 37.2: 装饰器类
正如导言中提到的,装饰器是一个可以应用于另一个函数以增强其行为的函数。语法糖等同于下面的内容: my_func = decorator(my_func)。但如果装饰器是一个类呢?语法仍然有效,只是现在 my_func 被替换为装饰器类的实例。如果这个类实现了 __call__()魔法方法,那么仍可以像使用函数一样使用 my_func:
class Decorator(object):
"""Simple decorator class."""
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print('Before the function call.')
res = self.func(*args, **kwargs)
print('After the function call.')
return res
@Decorator
def testfunc():
print('Inside the function.')
testfunc()
# Before the function call.
# Inside the function.
# After the function call.

请注意,从类型检查的角度来看,使用类装饰器装饰的函数将不再被视为 “函数”:
import types
isinstance(testfunc, types.FunctionType)
# False
type(testfunc)
# <class '__main__.Decorator'>

装饰方法
对于装饰方法,需要定义一个额外的__get__的方法:
from types import MethodType
class Decorator(object):
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print('Inside the decorator.')
return self.func(*args, **kwargs)
def __get__(self, instance, cls):
# Return a Method if it is called on an instance
return self if instance is None else MethodType(self, instance)
class Test(object):
@Decorator
def __init__(self):
pass
a = Test()

装饰器内部。
警告
类装饰器只为特定函数生成一个实例,因此使用类装饰器装饰方法时,该类的所有实例将共享同一个装饰器:
from types import MethodType
class CountCallsDecorator(object):
def __init__(self, func):
self.func = func
self.ncalls = 0 # Number of calls of this method
def __call__(self, *args, **kwargs):
self.ncalls += 1 # Increment the calls counter
return self.func(*args, **kwargs)
def __get__(self, instance, cls):
return self if instance is None else MethodType(self, instance)
class Test(object):
def __init__(self):
pass
@CountCallsDecorator
def do_something(self):
return 'something was done'
a = Test()
a.do_something()
a.do_something.ncalls # 1
b = Test()
b.do_something()
b.do_something.ncalls # 2

Section 37.3: 带参数的装饰器(装饰器工厂)
装饰器只有一个参数:要装饰的函数。没有办法传递其他参数。
但人们往往需要额外的参数。因此,诀窍在于创建一个接收任意参数并返回装饰器的函数。
装饰器函数
def decoratorfactory(message):
def decorator(func):
def wrapped_func(*args, **kwargs):
print('The decorator wants to tell you: {}'.format(message))
return func(*args, **kwargs)
return wrapped_func
return decorator
@decoratorfactory('Hello World')
def test():
pass
test()

装饰器想告诉你: Hello World
重要提示:
使用此类装饰器工厂时,必须用一对括号调用装饰器:
@decoratorfactory # Without parentheses
def test():
pass
test()

TypeError: decorator()缺少 1 个必填位置参数:func
装饰类
def decoratorfactory(*decorator_args, **decorator_kwargs):
class Decorator(object):
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print('Inside the decorator with arguments {}'.format(decorator_args))
return self.func(*args, **kwargs)
return Decorator
@decoratorfactory(10)
def test():
pass
test()

带参数的装饰器内部 (10,)
Section 37.4: 让装饰器看起来像被装饰的函数
装饰器通常会剥离函数元数据,因为它们并不相同。这可能会在使用元编程动态访问函数元数据时造成问题。元数据还包括函数的文档和名称。functools.wraps 通过将几个属性复制到包装函数,使被装饰的函数看起来像原始函数。
from functools import wraps
这两种包装装饰器的方法在隐藏原始函数已被装饰这一点上是相同的。除非你已经使用了其中一种,否则没有理由更倾向于使用函数版本而不是类版本。
作为一个函数
def decorator(func):
# Copies the docstring, name, annotations and module to the decorator
@wraps(func)
def wrapped_func(*args, **kwargs):
return func(*args, **kwargs)
return wrapped_func
@decorator
def test():
pass
test.__name__

'test'
作为一个类
class Decorator(object):
def __init__(self, func):
# Copies name, module, annotations and docstring to the instance.
self._wrapped = wraps(func)(self)
def __call__(self, *args, **kwargs):
return self._wrapped(*args, **kwargs)
@Decorator
def test():
"""Docstring of test."""
pass
test.__doc__

'Docstring of test.'
Section 37.5: 使用装饰器为函数计时
import time
def timer(func):
def inner(*args, **kwargs):
t1 = time.time()
f = func(*args, **kwargs)
t2 = time.time()
print('Runtime took {0} seconds'.format(t2-t1))
return f
return inner
@timer
def example_function():
#do stuff
example_function()

Section 37.6: 使用装饰器创建单例类
单例是一种将类的实例化限制为一个实例/对象的模式。使用装饰器,我们可以将一个类定义为单例,方法是强制该类返回一个现有的实例或创建一个新的实例(如果不存在)。
def singleton(cls):
instance = [None]
def wrapper(*args, **kwargs):
if instance[0] is None:
instance[0] = cls(*args, **kwargs)
return instance[0]
return wrapper
该装饰器可添加到任何类声明中,并确保最多创建一个类实例。任何后续调用都将返回已存在的类实例。
@singleton
class SomeSingletonClass:
x = 2
def __init__(self):
print("Created!")
instance = SomeSingletonClass() # prints: Created!
instance = SomeSingletonClass() # doesn't print anything
print(instance.x) # 2
instance.x = 3
print(SomeSingletonClass().x) # 3
因此,不管你是通过本地变量引用类实例,还是创建另一个 “实例”,得到的总是同一个对象。
