来自Python文档:
Objects are never explicitly destroyed; however, when they become
unreachable they may be garbage-collected. An implementation is
allowed to postpone garbage collection or omit it altogether — it is a
matter of implementation quality how garbage collection is
implemented, as long as no objects are collected that are still
reachable.
object.__init__(self[, ...])
Called after the instance has been created (by new()),
but before it is returned to the caller. [...]
object.__del__(self)
Called when the instance is about to be destroyed. [...]
因此,当调用
__init__
时,对象实例已经存在,因为它是由
__new__
创建的。但对于Python来说,无法保证
__del__
会被调用。
以下仅适用于Python的参考实现CPython。
注意(对于object.__del__(self)
)
del x不直接调用x.__del__()
——前者将x的引用计数减少1,只有当x的引用计数达到零时才会调用后者。[...]
在这里,__del__
仅在实例的引用计数降至0时调用。这与垃圾收集无关。做一个小实验:
>>> class A:
... def __del__(self): print "del"
...
>>> a = A()
>>> a = None
del
>>> import gc
>>> gc.disable()
>>> a = A()
>>> a = None
del
正如你所见,即使显式禁用GC,析构函数仍将被调用。
请注意,这也意味着如果您的对象层次结构中存在循环引用,您最终会得到一些对象,其中__del__
永远不会被调用,因为Python GC不能处理引用循环。
>>> a1 = A()
>>> a2 = A()
>>> a1.x = a2
>>> a2.x = a1
>>> a1 = None
>>> a2 = None
>>> import gc
>>> gc.collect()
4
>>> gc.garbage
[<__main__.A instance at 0x7f2c66a1d7e8>, <__main__.A instance at 0x7f2c66a1d830>]
__del__
类似于finally
子句,即无论如何都会执行的东西。 - Kris__del__
。 - chepner