如果您希望通过参数动态控制装饰器的行为(就像使用任何常规函数一样),您将使用装饰器工厂。例如,假设我想要一个在调用函数之前打印消息的装饰器。我可以这样做:
# Our decorator:
def print_message_decorator(func):
# The wrapper (what we replace our decorated function with):
def wrapper(*args, **kwargs):
print('A function is being called.')
result = func(*args, **kwargs)
return result
return wrapper
@print_message_decorator
def add(a, b):
return a + b
@print_message_decorator
def subtract(a, b):
return a - b
现在,如果我叫add
或subtract
每次都会打印A function is being called.
现在说,但是,其实我是想动态生成的装饰,我希望能够自定义每个装饰功能打印输出的信息。我通过将我的装饰器改为装饰器工厂来解决这个问题。
# Our decorator factory:
def print_message_decorator_factory(msg):
# The decorator it creates:
def print_message_decorator(func):
# The wrapper (what we replace our decorated function with):
def wrapper(*args, **kwargs):
print(msg)
result = func(*args, **kwargs)
return result
return wrapper
return print_message_decorator
@print_message_decorator_factory('Calling the add function.')
def add(a, b):
return a + b
@print_message_decorator_factory('Calling the subtract function.')
def subtract(a, b):
return a - b
现在如果我叫add
它打印Calling the add function.
,如果我叫subtract
它打印Calling the subtract function.
你自己已经回答了这个问题。装饰参数的装饰器是装饰器工厂。 – 2015-02-24 10:59:06
@MartijnPieters,但我无法做出完美适合的情况。谢谢 – igaurav 2015-02-24 11:02:02
然后,我不清楚你在这里问什么。 [一些装饰者](https://docs.python.org/2/library/functools.html#functools.wraps)带有参数,而[其他人不会](https://docs.python。组织/ 2 /库/ functions.html#属性)。 – 2015-02-24 11:15:03