我很好奇__del__python中的细节,何时以及为什么应该使用它以及它不应该用于什么.我已经学到了很难的方法,它不像人们对析构函数的天真期望,因为它不是__new__/ 的反面__init__.
class Foo(object):
def __init__(self):
self.bar = None
def open(self):
if self.bar != 'open':
print 'opening the bar'
self.bar = 'open'
def close(self):
if self.bar != 'closed':
print 'closing the bar'
self.bar = 'close'
def __del__(self):
self.close()
if __name__ == '__main__':
foo = Foo()
foo.open()
del foo
import gc
gc.collect()
Run Code Online (Sandbox Code Playgroud)
我在文档中看到,不保证__del__()在解释器退出时仍然存在的对象调用方法.
Foo解释器退出时存在的任何实例都关闭了吧?del foo还是gc.collect()......或者两者都没有?如果你想更好地控制那些细节(例如,当对象未被引用时应该关闭条形图)实现它的常用方法是什么?__del__被调用时能够保证所有的__init__已经叫什么名字?如果__init__举起怎么样?python constructor garbage-collection destructor reference-counting