1

私のタイトルは誤解を招く可能性があります。私の質問は、このコード スニペットから来ています。

class myDecorator(object):

    def __init__(self, f):
        print "inside myDecorator.__init__()"
        f() # Prove that function definition has completed

    def __call__(self):
        print "inside myDecorator.__call__()"

@myDecorator
def aFunction():
    print "inside aFunction()"

print "Finished decorating aFunction()"

#aFunction()

上記のコードを実行すると、次のような出力が得られます

inside myDecorator.__init__()
inside aFunction()
Finished decorating aFunction()

ただし、出力は

Finished decorating aFunction()

関数を装飾するだけで、コンストラクターを呼び出して myDecorator オブジェクトをaFunction()実行します。なぜそうなのですか?

デコレータに関する別の質問:

このリンクは、デコレータを次のように説明しています@ is just a little syntax sugar meaning "pass a function object through another function and assign the result to the original function.

これが参照する関数オブジェクト、別の関数、および元の関数は何ですか?

4

1 に答える 1