Bottom Page

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?
Quote
#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.
michalmonday likes this post
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures

Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Confusion with sublcassing a threading class, and inheritance bigmit37 2 119 Apr-08-2019, 09:28 AM
Last Post: DeaD_EyE
  Multiple inheritance - the right way ? denis_beurive 6 201 Feb-14-2019, 09:24 AM
Last Post: denis_beurive
  Inheritance Athul 7 551 Aug-11-2018, 06:48 PM
Last Post: yksingh1097
  Using Dictionaries in inheritance feduser 2 465 Jun-21-2018, 08:31 PM
Last Post: volcano63
  Inheritance private attributes vaison 5 677 May-03-2018, 09:22 AM
Last Post: vaison
  inheritance Arifattal 3 757 Jan-15-2018, 02:52 PM
Last Post: Arifattal
  Class Attributes Inheritance Harry_Potter 3 934 Nov-16-2017, 07:01 PM
Last Post: snippsat
  Multiple Inheritance using super() Sagar 2 2,323 Sep-08-2017, 08:58 AM
Last Post: Sagar
  Python dynamic inheritance ? harun2525 1 2,094 Apr-28-2017, 11:55 PM
Last Post: Mekire

Forum Jump:


Users browsing this thread: 1 Guest(s)