的方式來關閉資源方面的經理,又名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__
創建對象,然後將其作爲self
傳遞給__init__
。在__init__
出現異常之後,該對象通常沒有名稱(即f =
零件未運行),因此它們的引用計數爲0.這表示該對象正常刪除並調用__del__
。
>關閉資源的方式是上下文管理器,也就是with語句。 優秀的提示。不知道'with'可以用來以這種方式包含任何對象的範圍。 –
這個答案很有啓發性。感謝您的明確解釋! –