如何强制删除python对象?

时间:2011-07-21 07:09:59

标签: python constructor garbage-collection destructor reference-counting

我很好奇python中__del__的详细信息,何时以及为何应该使用它以及它不应该用于什么。我已经学到了很难的方法,它不像人们对析构函数的天真期望,因为它不是__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()

我在文档中看到,对于在解释器退出时仍然存在的对象,它是 not 保证__del__()方法。

  1. 如何保证解释器退出时存在的任何Foo个实例,条形图已关闭?
  2. 在上面的代码段中,条形图会在del foogc.collect()上关闭...或者两者都不关闭?如果你想更精细地控制这些细节(例如,当对象未被引用时应该关闭条形图)实现它的常用方法是什么?
  3. 调用__del__时是否保证已调用__init__?如果__init__被提出怎么办?

4 个答案:

答案 0 :(得分:69)

关闭资源的方法是上下文管理器,即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 =中发生异常后,该对象通常没有名称(即__del__部分未运行),因此它们的引用计数为0.这意味着该对象被正常删除并{{ 1}}被称为。

答案 1 :(得分:8)

一般来说,为了确保无论发生什么事情,都要使用

from exceptions import NameError

try:
    f = open(x)
except ErrorType as e:
    pass # handle the error
finally:
    try:
        f.close()
    except NameError: pass
无论finally块中是否存在错误,以及try块中发生的任何错误处理是否存在错误,

except块都将运行。如果您不处理引发的异常,则在finally块被激活后仍会引发该异常。

确保文件关闭的一般方法是使用“上下文管理器”。

http://docs.python.org/reference/datamodel.html#context-managers

with open(x) as f:
    # do stuff

这将自动关闭f

对于你的问题#2,bar在引用计数达到零时立即关闭,如果没有其他引用则在del foo上。

对象不是由__init__创建的,而是由__new__创建的。

http://docs.python.org/reference/datamodel.html#object.new

执行foo = Foo()实际发生了两件事时,首先要创建一个新对象__new__,然后对其进行初始化__init__。因此,在这两个步骤发生之前,你无法调用del foo。但是,如果__init__中存在错误,则仍会调用__del__,因为该对象实际上已在__new__中创建。

编辑:如果引用计数减少到零,则在删除时进行更正。

答案 2 :(得分:5)

也许您正在寻找context manager

>>> class Foo(object):
...   def __init__(self):
...     self.bar = None
...   def __enter__(self):
...     if self.bar != 'open':
...       print 'opening the bar'
...       self.bar = 'open'
...   def __exit__(self, type_, value, traceback):
...     if self.bar != 'closed':
...       print 'closing the bar', type_, value, traceback
...       self.bar = 'close'
... 
>>> 
>>> with Foo() as f:
...     # oh no something crashes the program
...     sys.exit(0)
... 
opening the bar
closing the bar <type 'exceptions.SystemExit'> 0 <traceback object at 0xb7720cfc>

答案 3 :(得分:2)

  1. 添加关闭所有栏的exit handler
  2. 当VM仍在运行时,当对象的引用数达到0时,会调用
  3. __del__()。这可能是由GC造成的。
  4. 如果__init__()引发异常,则假定该对象不完整,并且不会调用__del__()