使用父类B中父类A的方法

时间:2017-07-27 22:24:00

标签: python python-3.x inheritance multiple-inheritance superclass

我有一个A类:

class A(object):
   def pprint(x):
       print(x)

然后我有一个B级:

class B(object):
    def pprint(x):
        x += 1
        # find a way to call A.pprint(x)

然后我有一个孩子班:

class Child(B, A):
    pass

应该使用哪个:

child = Child()
child.pprint(1)
>>> 2

我可以对B进行更改但不能对A.进行更改。我不能直接在B中引用A.B永远不会直接实例化,总是通过子类。

2 个答案:

答案 0 :(得分:2)

您有两个选项可以从B类访问A方法而不从B继承A.

首先,您可以创建一个静态方法并从B中调用它。

class A(object):
   @staticmethod
   def pprint(x):
       print(x)

class B(object):
    def pprint(self, x):
        print(x + 1)
        A.pprint(x)

或者你可以像这样在B中继承A:

class A(object):
    def pprint(self, x):
        print(x)

class B(A):
    def pprint(self, x):
        print(x + 1)
        super(B, self).pprint(x)

然后,你的Child班只从B:

继承
class Child(B):
    pass


>>> c = Child()
>>> c.pprint(1)
2
1

好的,最新的解决方案。

import inspect

class C(B, A):
    def pprint(self, x):
        a_class = inspect.getmro(Child)[-2]
        a_class.pprint(self, x)

由于object将成为inspect.getmro(Child)中的最后一个结果,我们会跳过该结果,以获得最后一个结果,即A。然后我们调用该类的pprint方法。您还可以更确定地知道要调用的类的__name__,迭代inspect.getmro(Child)的结果并找到您想要的结果。

答案 1 :(得分:2)

解释之后 - 你需要的不是super()你需要像sibling_super()这样的东西来找到多继承链中的下一个类。您可以为此轮询Python的MRO,例如:

class A(object):

    def pprint(self, x):  # just to make it valid, assuming it is valid in the real code
        print(x)

class B(object):

    @staticmethod
    def sibling_super(cls, instance):
        mro = instance.__class__.mro()
        return mro[mro.index(cls) + 1]

    def pprint(self, x):
        x += 1
        self.sibling_super(B, self).pprint(self, x)

class Child(B, A):
    pass

child = Child()
child.pprint(1)  # 2
相关问题