Python Forum
Multiple Inheritance - Help pls!
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Multiple Inheritance - Help pls!
#1
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?
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Multiple inheritance - the right way ? denis_beurive 6 4,533 Feb-14-2019, 09:24 AM
Last Post: denis_beurive
  Multiple Inheritance using super() Sagar 2 7,245 Sep-08-2017, 08:58 AM
Last Post: Sagar

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020