Python Forum

Full Version: Multiple Inheritance - Help pls!
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
class Class(Superclass1, Superclass2):
    def __init__(self):
        super().__init__() #Superclass2
        super().__init__() #Superclass1

    def __repr__(self):
        '''I need it to work concatenating Superclass1 and Superclass2''' 
        return super().__repr__() + ' ' + super().__repr__()
Is it possible or will it inherit from Superclass1 in every method?
That's not how super works. If we do it your way:

class A(object):

    def __init__(self):
        print('A')

class B(object):

    def __init__(self):
        print('B')

class AB(A, B):

    def __init__(self):
        super().__init__()
        super().__init__()
        print('C')

if __name__ == '__main__':
    ab = AB()
We get:

Output:
A A C
Super just goes to the class after the current class in ab.__class__.__mro__ each time you call it. Super does not keep track of where the last super went. To go all the way through the MRO (method resolution order), you chain super:

class A(object):

    def __init__(self):
        super().__init__()
        print('A')

class B(object):

    def __init__(self):
        super().__init__()
        print('B')

class AB(A, B):

    def __init__(self):
        super().__init__()
        print('C')

if __name__ == '__main__':
    ab = AB()
And now we get:

B
A
C
Note that it is going to A.__init__ first, it's just that A.__init__'s super calls B.__init__ before it prints 'A'.

So concatenating the repr's will only work if you concatenate all the way up the chain. You might be able to work something out looping through ab.__class__.__mro__, but I expect there is a better solution for whatever your actual case is.