Search code examples
pythonpython-3.xinheritancemultiple-inheritancesuperclass

Use methods of parent class A from parent class B


I have a class A:

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

Then I have a class B:

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

Then I have a child class:

class Child(B, A):
    pass

Which should be used:

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

I can make changes to B but not to A. I cannot refer to A directly in B. B will never be instantiated directly, always via children class.


Solution

  • After the explanation - what you need is not super() you need something like sibling_super() to find the next class in the multiple inheritance chain. You can poll Python's MRO for that, for example:

    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