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

2019-07-04 01:05发布

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.

3条回答
倾城 Initia
2楼-- · 2019-07-04 01:49

__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.

查看更多
Fickle 薄情
3楼-- · 2019-07-04 02:07

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__'
查看更多
霸刀☆藐视天下
4楼-- · 2019-07-04 02:07

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.

查看更多
登录 后发表回答