Python:无法使用 super() 调用父类析构函数

标签 python destructor super

我无法从子类的析构函数中调用父类的析构函数。 请检查以下代码:

class BaseClass(object):
    def __del__(self):
        print 'BaseClass->Destructor'

class DerivativeClass(BaseClass):
    def __del__(self):
        print 'DerivativeClass->Destructor'
        #Invoke destructor of the base class, it works 
        BaseClass.__del__(self)           
        #Doesn't work
        #super(DerivativeClass, self).__del__() 

instance = DerivativeClass()

当我在 DerivativeClass.__del__() 中使用 super(DerivativeClass, self).__del__() 时,出现以下错误:

Exception TypeError: 'must be type, not None' in <bound method 
DerivativeClass.__del__ of <__main__.DerivativeClass object at 0xb73a682c>> ignored

问题:

为什么我不能在子类的析构函数中使用 super 而它在子类的构造函数中完全没问题?

最佳答案

这似乎只发生在运行时退出(因为 DerivativeClassNone)。

这很好用:

class BaseClass(object):
    def __del__(self):
        print 'BaseClass->Destructor'

class DerivativeClass(BaseClass):
    def __del__(self):
        print 'DerivativeClass->Destructor'
        super(DerivativeClass, self).__del__() 

instance = DerivativeClass()
del instance

这也很好用:

class BaseClass(object):
    def __del__(self):
        print 'BaseClass->Destructor'

class DerivativeClass(BaseClass):
    def __del__(self):
        print 'DerivativeClass->Destructor'
        super(type(self), self).__del__() 

instance = DerivativeClass()

还有这个:

class BaseClass(object):
    def __del__(self):
        print 'BaseClass->Destructor'

class DerivativeClass(BaseClass):
    def __del__(self):
        print 'DerivativeClass->Destructor'
        super(DerivativeClass, self).__del__() 

def someScope ():
    instance = DerivativeClass()

someScope ()

在片段 1 和片段 3 中,我确保实例在类之前结束。在片段 2 中,我以一种非常丑陋的方式绕过了整个问题。

关于Python:无法使用 super() 调用父类析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22972720/

相关文章:

python - 如何解析带有分数的字符串以获取 '/'两边的数字

c++ - 动态对象析构函数中的异常

c++ - 为什么析构函数只被调用一次?

python - Kivy/Python 中 super 的属性错误

python - Matplotlib、Jupyter : Have annotation appearing when hovering over plot

python - Django url,不同的正则表达式?

Python MySQLdb唯一记录,忽略错误

c# - 对象实例丢失时如何处理它的引用

python - 为什么我的 Python 继承/ super 示例不起作用?

java - 构造函数中的 super()