1

When working with multiple inheritance, I'm trying to understand why it works if you refer to the parents' class names in the child class, but it does not work if you use super(). Any help is appreciated.

#DOES NOT WORK WITH super()
#Parent 1 class
class Husband:
    def __init__(self,strength):
        self.strength = strength
#Parent 2 class
class Wife:
    def __init__(self,looks):
        self.looks = looks
#Child class
class Son(Husband,Wife):
    def __init__(self,strength,looks):
        super().__init__(self,strength)
        super().__init__(self,looks)

son = Son('Goliath','GQ')
print(son.strength,son.looks)



#WORKS WHEN CALLING PARENT CLASS NAMES
#Parent 1 class
class Husband:
    def __init__(self,strength):
        self.strength = strength
#Parent 2 class
class Wife:
    def __init__(self,looks):
        self.looks = looks
#Child class
class Son(Husband,Wife):
    def __init__(self,strength,looks):
        Husband.__init__(self,strength)
        Wife.__init__(self,looks)

son = Son('Goliath','GQ')
print(son.strength,son.looks)
PythonNoob
  • 93
  • 9
  • 1
    Does this answer your question? [How does Python's super() work with multiple inheritance?](https://stackoverflow.com/questions/3277367/how-does-pythons-super-work-with-multiple-inheritance) – Alias Cartellano Apr 30 '22 at 21:20
  • 1
    I'd highly recommend this video on the matter: [super, Python's most misunderstood feature.](https://www.youtube.com/watch?v=X1PQ7zzltz4) – Alexander Apr 30 '22 at 21:48
  • @Alexander Thank you for your input. I'm definitely going to check it out! – PythonNoob Apr 30 '22 at 23:13

2 Answers2

3

Super doesn't mean "parent", it means "next in line in the MRO of this object".

So if you make a class that you want to be inherited from, you should probably be calling super() in that parent class as well.

If self is a Son object, then within the body of the Husband.__init__(self) method, super() delegates to Wife, not to general object. You should only need one super().__init__ call within Son, and then the super call in Husband.__init__ can delegate to Wife.__init__. (I'm not sure subclassing is the correct relationship for this case: I wouldn't say a Son is-a Wife). You may also need to update the __init__ signatures to accept arbitrary **kwargs so that everything can be passed along in a compatible way.

Here's a blog post that I think is helpful: https://rhettinger.wordpress.com/2011/05/26/super-considered-super/

There's a video on YouTube with the same title "Super Considered Super" that I think is helpful as well.

Dennis
  • 2,249
  • 6
  • 12
1

In short, if your class has multiple inheritance, a plain call to super() always refer to the Husband class.

You may want to look for a concept called MRO (Method resolution order).

tyson.wu
  • 704
  • 5
  • 7