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

时间:2014-04-09 19:55:12

标签: python destructor super

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

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()

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

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

问题:

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

1 个答案:

答案 0 :(得分:5)

这似乎只在运行时退出时发生(因为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中,我以相当丑陋的方式围绕整个问题。