PythonNoob
PythonNoob

Reputation: 141

Multiple Inheritance -- super() vs Parent class names

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)

Upvotes: 2

Views: 914

Answers (2)

Dennis
Dennis

Reputation: 2304

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.

Upvotes: 3

tyson.wu
tyson.wu

Reputation: 734

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).

Upvotes: 1

Related Questions