在这里,我们用两个不同的名称和两个不同的年龄运行了两次display info。
现在,每当我们运行display info时,我们的装饰器还添加了打印换行函数前后一行的功能。
def decorator_function(original_function):
def wrapper_function(*args, **kwargs):
print('Executed Before', original_function.__name__)
result = original_function(*args, **kwargs)
print('Executed After', original_function.__name__, '\n')
return result
return wrapper_function
@decorator_function
def display_info(name, age):
print('display_info ran with arguments ({}, {})'.format(name, age))
display_info('Mr Bean', 66)
display_info('MC Jordan', 57)
输出:
Executed Before display_info
display_info ran with arguments (Mr Bean, 66)
Executed After display_info
Executed Before display_info
display_info ran with arguments (MC Jordan, 57)
Executed After display_info
现在让我们继续让decorator函数接受参数。
例如,假设我想为包装器中的所有这些打印语句添加一个可定制的前缀。
现在这将是一个很好的候选参数的装饰。
我们传入的参数就是那个前缀。现在为了做到这一点,我们将添加另一个外层到我们的装饰器中,我将把这个函数称为前缀装饰器。
def prefix_decorator(prefix):
def decorator_function(original_function):
def wrapper_function(*args, **kwargs):
print(prefix, 'Executed Before', original_function.__name__)
result = original_function(*args, **kwargs)
print(prefix, 'Executed After', original_function.__name__, '\n')
return result
return wrapper_function
return decorator_function
@prefix_decorator('LOG:')
def display_info(name, age):
print('display_info ran with arguments ({}, {})'.format(name, age))
display_info('Mr Bean', 66)
display_info('MC Jordan', 57)
输出:
LOG: Executed Before display_info
display_info ran with arguments (Mr Bean, 66)
LOG: Executed After display_info
LOG: Executed Before display_info
display_info ran with arguments (MC Jordan, 57)
LOG: Executed After display_info
现在我们在包装器函数的print语句之前有了LOG:前缀,你可以随时更改它。