Python装饰器到函数变量

时间:2013-09-06 23:00:10

标签: python python-decorators

在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()

提前致谢。

1 个答案:

答案 0 :(得分:5)

a_function_with_status_display = status_display(a_function)
a_function_with_call_counter = call_counter(a_function)

您似乎能够编写装饰器,但您不知道他们在做什么?