在 python 2.x 中我应该调用 object.__del__ 吗?
在Python 3.x 中,所有类都是object
的子类。在 2.x 中,您必须显式声明 class MyClass(object)
。而且,由于我试图编写尽可能多的 3.x 兼容代码,因此我对 object
进行了子类化。
在我的程序中,我使用了 __del__ 方法,我想知道我是否应该调用 object.__del__(self) ,或者是否可以神奇地解决这个问题?
谢谢, 韦恩
编辑: 看来我的意思有些混乱 - 在文件中它指出:
如果基类具有
__del__()
方法,则派生类的__del__()
方法(如果有)必须显式调用它以确保正确删除基类实例的类部分。
所以我想知道我是否需要:
def __del__(self):
object.__del__(self)
或一些合适的替代方案。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
__del__
不应该被调用。当对象不再有引用并被收集时,析构函数会自动执行。相反,您不调用
__init__
,而是在对象创建时自动处理。调用 __del__ 不会破坏对象,这样做实际上可能会导致意外的行为。__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.检查 http://docs.python.org/reference/datamodel.html#basic-自定义和http://docs.python.org/library/gc .html#module-gc。您不需要在对象上调用
__del__
方法,因为垃圾收集器应该为您执行此操作。只需编写一个正确的 __del__ 方法,Python 就会为您处理它。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.好吧,
object
实际上没有__del__
方法,所以不,您不需要调用它。Well,
object
doesn't actually have a__del__
method, so no, you don't need to call it.