あなたがやっていることはまったくうまくいっていて、Pythonicに見えます。 contextlib
標準ライブラリにはすでに類似点がありますが、Close
メソッドの名前をclose
に変更する必要があります。
import contextlib
with contextlib.closing(thing):
print thing
これを代わりに使用することをおすすめします。結局のところ、Pythonメソッドの推奨命名規則はall_lowercase_with_underscores
です。
class Foo(object):
def __init__(self, filename):
self.filename = filename
def __enter__(self):
self.fd = open(self.filename)
def __exit__(self, exc_type, exc_value, traceback):
self.fd.close()
と使用:ブロックwith
を入力し、出るとき
with Foo('/path/to/file') as foo:
# do something with foo
方法__enter__
と__exit__
が暗黙的に呼び出されます
出典
2013-08-12 06:36:57
tom
これは良いようです。あなたのクラスでデストラクタを使うこともできます。 – akiniwa
私はデストラクタ(つまり '__del__')を使わないでください。それがいつ呼び出されるのかについて、本当に考えるのは難しいです。ここで受け入れられた答えを参照してください:http://stackoverflow.com/questions/1935153/del-method-being-called-in-python-when-it-is-not-expected – tom