Python3,超级版

2024-04-23 11:14:37 发布

您现在位置:Python中文网/ 问答频道 /正文

<>我在定义的类中有一个^ {CD1>}方法,用来删除在cType接口中调用C++新创建的C++对象。我想在类的一个实例被破坏时删除这些对象。我有一个片段显示在这里:

class Graph(QtCore.QObject):
    def __init__(self):
        super().__init__()
        #list of objects created by calls to ctypes to create pointers to C++ objects which are instantiated with C++ new 
        self.graphs = []

    def __del__(self):
        print("in delete method")
        for graph in self.graphs:
            # call the C++ delete to free the storage used by this graph
            myctypes.graphDelete(graph)
        super().__del__()

当我的图形类的实例被删除时,调用^ {< CD1>}方法,我看到我的打印语句,当我在C++代码中的析构函数方法中设置断点时,如预期的那样,它删除对象。但是,当我的__del__方法调用super().__del__()时,我得到错误消息:

^{pr2}$

如何确保父类(QtCore.QObject)如果我在子类中定义我自己的__del__方法,则会删除,还是父类将自动删除?在


Tags: to对象实例方法selfobjects定义init
2条回答

__del__的作用不是删除对象:在对象被自动删除之前,它被称为。因此,如果您的父类不定义__del__,就可以了。如果有麻烦,请不要打电话给super().__del__()。在

有鉴于此,对象没有默认的__del__的原因是,在引用循环的情况下,带有{}的对象没有被垃圾回收(直到python3.4)。有关详细信息,请阅读gc.garbage in Python 3.3和{a2}的文档。在

从中派生的类没有__del__()。所以尝试调用它是一个错误。在

现在,如果您希望在多重继承场景中使用您的类,那么方法解析顺序(MRO)中的下一个类可能实际上不是类的父类。而那个类,不管它是什么,都可能有一个__del__()方法。因此,如果您关心这种情况,您可以使用try并吞下AttributeError,或者使用hasattr(),或者使用{}和一个虚拟lambda作为默认值。在

以下是每个示例:

# there is a minor bug here, can you guess what it is?
try:
    super().__del__(self)
except AttributeError:
    pass

# better version of the above
s = super()
try:
    s.__del__
except AttributeError:
    pass
else:
    s.__del__(self)

s = super()
if hasattr(s, "__del__"): 
    s.__del__(self)

getattr(super(), "__del__", lambda self: None)(self)

相关问题 更多 >