在 python 2.x 中我应该调用 object.__del__ 吗?

发布于 2024-10-03 00:54:53 字数 530 浏览 0 评论 0原文

在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

少年亿悲伤 2024-10-10 00:54:53

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

花落人断肠 2024-10-10 00:54:53

检查 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.

攒眉千度 2024-10-10 00:54:53

好吧,object 实际上没有 __del__ 方法,所以不,您不需要调用它。

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

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__'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文