Pythonのデコレーターは、関数の関数を呼び出すこととまったく同じですか?

StackOverflow https://stackoverflow.com/questions/3074672

質問

やっていると思った

@f
def g():
   print 'hello'

まったく同じです

def g():
   print 'hello'
g=f(g)

しかし、私はこのコードを持っていて、ContextLib.ContextManagerを使用します。

@contextlib.contextmanager
def f():
    print 1
    yield
    print 2
with f:
    print 3

動作し、生み出します 1 3 2

そして、私がそれを変更しようとしたとき

def f():
    print 1
    yield
    print 2
f=contextlib.contextmanager(f)
with f:
    print 3

私は得ます AttributeError: 'function' object has no attribute '__exit__'

何が足りないの? ContextLib.ContextManagerに特にブラックマジックがありますか、それともデコレーターがどのように機能するか誤解していますか?

役に立ちましたか?

解決

はい、デコレーターは関数を呼び出して返された値に割り当てることとまったく同じです

この場合、あなたが関数を呼び出していないためにエラーが発生しますので、正しいコードは

def f():
    print 1
    yield
    print 2

f=contextlib.contextmanager(f)
with f():
    print 3

また、コードをテストしたかどうかはわかりません。

@contextlib.contextmanager
def f():
    print 1
    yield
    print 2
with f:
    print 3

エラー:

    with f:
AttributeError: 'function' object has no attribute '__exit__'
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top