0

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

前もって感謝します。

4

1 に答える 1

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

あなたはデコレータを書くことができるようですが、彼らが何をするのか分かりませんか?

于 2013-09-06T23:02:58.610 に答える