Python 在不通过Mixin执行父方法的情况下调用祖父母方法

Python 在不通过Mixin执行父方法的情况下调用祖父母方法,python,multiple-inheritance,Python,Multiple Inheritance,我需要重写父方法并通过mixin调用祖父母方法。可能吗 例如:A和B是库类 class A(object): def class_name(self): print "A" class B(A): def class_name(self): print "B" super(B, self).class_name() # other methods ... 现在我需要重写B中的class\u name方法,并调用它的su

我需要重写父方法并通过mixin调用祖父母方法。可能吗

例如:
A
B
是库类

class A(object):
    def class_name(self):
        print "A"


class B(A):
    def class_name(self):
        print "B"
        super(B, self).class_name()
    # other methods ...
现在我需要重写
B
中的
class\u name
方法,并调用它的super

class Mixin(object):
    def class_name(self):
        print "Mixin"
        # need to call Grandparent class_name instead of parent's
        # super(Mixin, self).class_name()


class D(Mixin, B):
    # Here I need to override class_name method from B and call B's super i.e. A's class_name, 
    # It is better if I can able to do this thourgh Mixin class. (
    pass
现在,当我调用
D().class_name()
时,它应该只打印
“Mixin”和“A”
。不是“B”

一种方法是使用,但如果用户编写
类D(B,Mixin)
,则该方法可能会中断

让我示范一下:

class A(object):
    def class_name(self):
        print "A"


class B(A):
    def class_name(self):
        print "B"
        super(B, self).class_name()
    # other methods ...

class Mixin(object):
    def class_name(self):
        print "Mixin"
        # need to call Grandparent class_name instead of parent's
        # super(Mixin, self).class_name()


class D(Mixin, B):
    # Here I need to override class_name method from B and call B's super i.e. A's class_name, 
    # It is better if I can able to do this thourgh Mixin class. (
    pass

class E(B, Mixin): pass

import inspect
print inspect.getmro(D) # returns tuple with (D, Mixin, B, A, object)
print inspect.getmro(E) # returns tuple with (E, B, A, Mixin, object)

因此,如果您拥有控制权,并且能够确保始终首先获得
Mixin
。您可以使用
getmro()
获取祖父母并执行它的
class\u name
函数。

可能可以使用
mro
(方法解析顺序)来完成,但我认为如果您编写
class D(B,Mixin)
,它会崩溃。解决方案: