In python 2.x should I call object.__del__?

牧云@^-^@ 提交于 2019-12-10 21:29:31

问题


In Python 3.x all classes are subclasses of object. In 2.x you have to explicitly state class MyClass(object). And, as I'm trying to write as much 3.x compatible code as possible, I'm subclassing object.

In my program, I'm using the __del__ method, and I wanted to know if I should be calling object.__del__(self), or if that's magically taken care of?

Thanks, Wayne

EDIT: It appears there is some confusion what I mean - in the documents it states:

If a base class has a __del__() method, the derived class’s __del__() method, if any, must explicitly call it to ensure proper deletion of the base class part of the instance.

So I wanted to know if I needed:

def __del__(self):
    object.__del__(self)

or some suitable alternative.


回答1:


Well, object doesn't actually have a __del__ method, so no, you don't need to call it.

>>> object().__del__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute '__del__'



回答2:


__del__ isn't meant to be called. Destructors are executed automatically when the object has no more references and is collected.

Inversely, you don't call __init__, but is taken care of automatically on object creation. Calling __del__ won't destruct the object and doing so may actually lead to unexpected behavior.




回答3:


Check http://docs.python.org/reference/datamodel.html#basic-customization and http://docs.python.org/library/gc.html#module-gc. You don't need to call the __del__ method on your object, because the garbage collector is supposed to do it for you. Just write a correct __del__ method and python will take care of it for you.



来源:https://stackoverflow.com/questions/4199653/in-python-2-x-should-i-call-object-del

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!