これは、あなたが作成することができ、最も基本的なコンテキストマネージャである:
class UselessContextManager(object):
def __enter__(self):
pass
def __exit__(self, type, value, traceback):
pass
with UselessContextManager() as nothing:
print(nothing is None)
あなたが実際にプロセスフローがどのように見えるために少し感触を取得したい場合は、してみてください。この1:
class PrintingContextManager(object):
def __init__(self, *args, **kwargs):
print('Initializing with args: {} and kwargs: {}'.format(args, kwargs))
def __enter__(self):
print('I am entering the context')
print('I am returning 42')
return 42
def __exit__(self, type, value, traceback):
print('And now I am exiting')
print('Creating manager')
manager = PrintingContextManager()
print('Entering with block')
with manager as fnord:
print('Fnord is {}'.format(fnord))
print('End of context')
print('Out of context')
出力:
Creating manager
Initializing with args:() and kwargs: {}
Entering with block
I am entering the context
I am returning 42
Fnord is 42
End of context
And now I am exiting
Out of context
コードを次のように変更してください。 type, value, traceback
を印刷し、with
ブロック内で例外を発生させます。
>>> f = open('/tmp/spanish_inquisition.txt', 'w')
>>> f.__enter__
<function TextIOWrapper.__enter__>
>>> f.__exit__
<function TextIOWrapper.__exit__>
:あなたはファイルは常にコンテキストマネージャであることを見ることができます
thing = ContextManager()
try:
stuff = thing.__enter__()
except Exception as e:
stuff.__exit__(type(e), e.args[0], e.__traceback__)
Though truthfully it's a bit different
:
あなたが見ることができるように、with
構文がためほとんどわずかです
ファイルがContextManagerである可能性がありますスーパークラスを継承せずに、あるいはインタフェースを明示的に実装することなく、2つのメソッドを実装するだけです。繰り返しますが、私はこの言語を初めて使う人です。
がであり、明示的にインターフェイスを実装しています。 Javaでは、どのインタフェースを遵守するかを指定する必要があります。 Pythonでは、あなたはそれを行うだけです。ファイルのようなオブジェクトが必要ですか? .read()
メソッドを追加します。たぶん、.seek()
,.open()
、および.close()
が期待するものに依存します。しかし、Pythonでは...
it = DecoyDuck()
if it.walks_like_a_duck() and it.talks_like_a_duck() and it.quacks_like_a_duck():
print('It must be a duck')
ファイル*はコンテキストマネージャです。 – user2357112
オープン後の 'with'は、書き込み後にファイルを安全に閉じます。 – n1c9
https://www.python.org/dev/peps/pep-0343/を読んだことがありますか? –