Last active
August 29, 2015 14:27
-
-
Save zaki-yama/c20c608efd1e91df909b to your computer and use it in GitHub Desktop.
[python] withステートメントのサンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
class Foo(object): | |
def bar(self): | |
print self.foo | |
def __init__(self, foo): | |
u"""今回直接は関係ない""" | |
print '__init__' | |
self.foo = foo | |
def __enter__(self): | |
u"""with ステートメントに入る時に呼ばれる | |
このメソッドの戻り値が | |
`with Foo('hoge') as f:` の `f` になるため | |
return self する. | |
""" | |
print '__enter__' | |
return self | |
def __exit__(self, exc_type, exc_value, traceback): | |
u"""with ステートメントを出る時に呼ばれる | |
with ステートメント内で例外が送出された場合 | |
exc_type, exc_value, traceback に情報が渡される. | |
例外が送出されなかった場合はすべての引数に None が渡される. | |
また、このメソッドが True を返すと例外を握りつぶし | |
False を返すと例外は伝搬される. | |
""" | |
print exc_type | |
print exc_value | |
print traceback | |
print '__exit__' | |
with Foo('hoge') as f: | |
f.bar() | |
raise ValueError('foo') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment