在 Python 中,有没有办法将不同的装饰器作为变量分配给函数?
例如(以下代码显然不会执行):
def status_display(function):
def body():
print("Entering", function.__name__)
function()
print("Exited", function.__name__)
return body
def call_counter(function):
counter = 0
def body():
function()
nonlocal counter
counter += 1
print(function.__name__, 'had been executed', counter, 'times')
return body
def a_function():
print('a_function executes')
# problems start here
# is there a working alternative to this false syntax?
@status_display
a_function_with_status_display = a_function()
@call_counter
a_function_with_call_counter = a_function()
# for an even crazier feat
# I knew this wouldn't work even before executing it
a_function_with_status_display = @status_display a_function()
a_function_with_call_counter = @call_counter a_function()
提前致谢。