リソースを閉じる方法は、コンテキストマネージャー、別名with
ステートメントです。
class Foo(object):
def __init__(self):
self.bar = None
def __enter__(self):
if self.bar != 'open':
print 'opening the bar'
self.bar = 'open'
return self # this is bound to the `as` part
def close(self):
if self.bar != 'closed':
print 'closing the bar'
self.bar = 'close'
def __exit__(self, *err):
self.close()
if __name__ == '__main__':
with Foo() as foo:
print foo, foo.bar
出力:
opening the bar
<__main__.Foo object at 0x17079d0> open
closing the bar
2)Pythonのオブジェクトは、参照カウントが0のときに削除されます。この例でdel foo
は、は最後の参照を削除するため、__del__
即座に呼び出されます。GCはこれに関与していません。
class Foo(object):
def __del__(self):
print "deling", self
if __name__ == '__main__':
import gc
gc.disable() # no gc
f = Foo()
print "before"
del f # f gets deleted right away
print "after"
出力:
before
deling <__main__.Foo object at 0xc49690>
after
はgc
、自分や他のほとんどのオブジェクトを削除することとは何の関係もありません。自己参照または循環参照のために、単純な参照カウントが機能しない場合にクリーンアップするためにあります。
class Foo(object):
def __init__(self, other=None):
# make a circular reference
self.link = other
if other is not None:
other.link = self
def __del__(self):
print "deling", self
if __name__ == '__main__':
import gc
gc.disable()
f = Foo(Foo())
print "before"
del f # nothing gets deleted here
print "after"
gc.collect()
print gc.garbage # The GC knows the two Foos are garbage, but won't delete
# them because they have a __del__ method
print "after gc"
# break up the cycle and delete the reference from gc.garbage
del gc.garbage[0].link, gc.garbage[:]
print "done"
出力:
before
after
[<__main__.Foo object at 0x22ed8d0>, <__main__.Foo object at 0x22ed950>]
after gc
deling <__main__.Foo object at 0x22ed950>
deling <__main__.Foo object at 0x22ed8d0>
done
3)見てみましょう:
class Foo(object):
def __init__(self):
raise Exception
def __del__(self):
print "deling", self
if __name__ == '__main__':
f = Foo()
与える:
Traceback (most recent call last):
File "asd.py", line 10, in <module>
f = Foo()
File "asd.py", line 4, in __init__
raise Exception
Exception
deling <__main__.Foo object at 0xa3a910>
オブジェクトはで作成され、として__new__
に渡さ__init__
れself
ます。の例外の後__init__
、オブジェクトには通常名前がないため(つまり、f =
パーツは実行されません)、参照カウントは0になります。これは、オブジェクトが正常に削除されて__del__
呼び出されることを意味します。