In python 2.x should I call object.__del__?
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 bas开发者_开发知识库e 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.
__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.
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.
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__'
精彩评论