调用祖父表方法而不通过Mixin执行父方法

时间:2016-09-05 13:38:38

标签: python multiple-inheritance

我需要覆盖Parent方法并通过mixin调用Grandparent方法。可能吗?

例如:AB是库类。

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_name中的B方法,并将其称为“超级”。

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" and "A"。不是" B"

1 个答案:

答案 0 :(得分:1)

一种方法是使用inspect.getmro(),但如果用户写class 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_name功能。