Why super().__init() ¿?

Hi!! I have read a lot and search in stackoverflow, but I do not really get what does super() do.
Can somebody explain to me in simple words why is it used? what would happen if it gets removed?

Thanks a lot!

It is for class inheritance. Suppose you have some class defined say A. Now you want to extend this class with a few modifications. Note that you don’t want to create a new class from scratch as there could be many things in common with class A that you don’t want to re-write. So you inherit the class and then define the modifications. In doing so, if you are modifying the constructor __init__ as well, then you should call super().__init__() as well, the arguments of __init__ depending on those of the parent class A. super() is basically refering to the parent class of the new class.

For example if you want to create a class B inheriting from class A then:

class A:
    def __init__(self):
        self.a1 = 0
        self.b1 = 0
class B(A):
    def __init__(self, a, b):
         super().__init__()  # this automatically does the thing writtent in __init__ of class a
         self.a = a
         self.b = b

So if you remove the super() line B won’t have a1 and b1 as its variables.
A good answer on stack overflow is here: https://stackoverflow.com/questions/576169/understanding-python-super-with-init-methods

3 Likes

OK, now I get, so super call parent class constructor so that you can init the proper variables, Thanks a lot, really very good answer.
You can use super to call more methods of the parent class

class person():
	def __init__(self):
		self.name="peter"
		self.surname="mageneto"
	def bye(self):
		print("hello")
class student(person):
	def __init__(self):
		self.subject = "maths"
class studentB(person):
	def __init__(self):
		self.subject = "maths"
		self.surname="parker"
		super().__init__()
		super().bye()
		self.bye()
	def bye(self):
		print("bye")
b = studentB()

I edit my answer, I called the wrong method!! Perfect now!!!
Thanks a lot for your help!