2016-12-21 6 views
2

私はPythonインタプリタ(2.7.13)で次のように行っている:オブジェクトは "with"ブロック内でどのようにインスタンス化されますか?

>>> class test: 
...  def __init__(self): 
...    print "Object has been constructed!" 
...  def __enter__(self): 
...    print "Entering with" 
...  def __exit__(self, type, value, traceback): 
...    print "Exiting with" 
... 
>>> 
>>> t1 = test() 
Object has been constructed! 
>>> print t1 
<__main__.test instance at 0x7fed5383e3b0> 
>>> 
>>> with test() as t1: 
...  print "Inside 'with' block" 
...  print t1 
... 
Object has been constructed! 
Entering with 
Inside 'with' block 
None 
Exiting with 

私の質問は:なぜwithブロック内print出力noneしていますか?オブジェクトはwithによってインスタンス化されているようですが(少なくとも、コンストラクタへの呼び出しがあることがわかりますが)、名前空間内にt1が存在しないようです。それは普通ですか?

答えて

4

__enter__None(暗黙的に)返されるため、Noneが印刷されます。

はサンプル次の点を考慮

class test: 
    def __init__(self): 
     print "Object has been constructed!" 
    def __enter__(self): 
     print "Entering with" 
     return 5 
    def __exit__(self, type, value, traceback): 
     print "Exiting with" 

with test() as t1: 
    assert t1 == 5 

AssertionError

が提起されていない、したがって、我々は t1は、一般的には5

に等しい知っている、with ctx_mgr as something:somethingに割り当てられた値ではなく、厳密ctx_mgr、何もすることができます。 ctx_mgrでなければならない場合、with ... as ...構成は冗長である。

+0

ありがとうございました、この明確な例の小道具! –

3

self(または必要に応じて他のオブジェクト)をコンテキストマネージャメソッド__enter__に返す必要があります。この関数の結果はasに割り当てられている:python context manager typesに説明して、それがどのように動作するか

class test: 
    ... 
    def __enter__(self): 
      print("Entering with") 
      return self 
    ... 

を。

+0

ありがとうございました。正しく理解すれば、 '__enter__'が' self'を返さない限り、t1は 'None'型です。それは理にかなっている。 –

+0

'return'文にwitoutを打ち込むpython関数は暗黙的に' None'を返します。 '__enter__'はあなたが望むものを返すことができます。 –

関連する問題