pythonのwith構文には、withの開始と終了に実行される特殊メソッドがあることを知りました。それで下記のコードを実行したところ、exit()の中でインスタンスメソッドを実行するとそれ以降の処理が実行されません。組み込み関数や、クラス外で定義した関数は問題なく処理されます。
この理由がわかりません。どなたか教えていただけないでしょうか?
また、main()のtry文で例外が発生しているのですが、なぜ例外が発生してしまっているのかもわかりません。合わせてご教授いただけると大変助かります。
よろしくお願い致します。
実行環境
Mac OS X 10.9.5
Python 3.4.3
lang
1class withtest: 2 3 def __enter__(self): 4 print('__enter__') 5 return self 6 7 def __exit__(self, exc_type, exc_value, traceback): 8 print('__exit__') 9 print("self = %s" % self) 10 print("exc_type = %s" % exc_type) 11 print("exc_value = %s" % exc_value) 12 print("traceback = %s" % traceback) 13 14 outer_hello() 15 inner_hello() 16 print('exitを抜けます') 17 18 def close(self): 19 print('close') 20 21 def inner_hello(): 22 print('hello from inner') 23 24def outer_hello(): 25 print('hello from outer') 26 27def main(): 28 try: 29 with withtest() as w: 30 print(type(w)) 31 except: 32 print('例外発生') 33 34if __name__ == '__main__': 35 main() 36 37# => 38# __enter__ 39# <class '__main__.withtest'> 40# __exit__ 41# self = <__main__.withtest object at 0x1090f7a90> 42# exc_type = None 43# exc_value = None 44# traceback = None 45# hello from outer 46# 例外発生
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2015/06/16 00:06