parent class A 从 parent class B 使用方法

Use methods of parent class A from parent class B

我有一个class答:

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

那我有一个class B:

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

那我有一个child class:

class Child(B, A):
    pass

应该使用哪个:

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

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

您有几个选项可以从 B class 访问 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 class 只继承自 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。然后我们调用 class 的 pprint 方法。如果您知道要调用的 class 的 __name__,您还可以迭代 inspect.getmro(Child) 的结果并找到您想要的结果。

经过解释 - 你需要的不是 super() 你需要像 sibling_super() 这样的东西来找到多重继承链中的下一个 class。您可以为此轮询 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