How Does super().__init__() Work in Python Classes?

0
6
Asked By CuriousCoder42 On

I'm trying to understand how the super().__init__() method and the Class.__init__() work in Python, especially in the context of inheritance. In my example, I have a Rectangle class with an __init__ method that takes height and width. Then, I have a Square class that inherits from Rectangle and seemingly calls the Rectangle's __init__ method through super(). I also tried calling it directly using Rectangle.__init__(). Can anyone explain how these calls impact the instance attributes of the Square object?

2 Answers

Answered By LogicLover77 On

Super is essentially a way to access methods from a parent class, like Rectangle in this case. When you create a Square object, it inherits the properties and methods from Rectangle. So, even though you define a new __init__ in Square, calling super().__init__(side, side) effectively runs the Rectangle’s __init__ method, setting the height and width for your instance. It's more about the inheritance chain and less about the direct calling of methods!

QuestionAsker04 -

Got it! So super() helps maintain the hierarchy and makes it easy to call the base class's methods. That's helpful!

Answered By PythonPro99 On

If you want a deeper understanding, I found this video really helpful. It goes into the mechanics of super and inheritance in detail. [Check it out here](https://youtu.be/X1PQ7zzltz4?si=RTloEyO4Cx-ivTWJ).

SkepticFan98 -

Is a 21-minute video really the best way to grasp this? Seems a bit long!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.