I have a question about inheritance in python and although I checked info I couldn't get it clear. When doing class inheritance in Python, what is the difference in inheriting it with super(). init ... or with student. init ... considering the code.
class persona:
def __init__(self, nombre, edad):
self.nombre = nombre
self.edad = edad
def presentarse(self):
print(f"Hola, me llamo {self.nombre}")
class estudiante(persona):
def __init__(self, nombre, edad):
super().__init__(nombre, edad)
class estudiante2(persona):
def __init__(self, nombre, edad):
persona.__init__(self, nombre, edad)
if __name__ == "__main__":
Juan = estudiante("juan", 99)
Juan.presentarse()
Pedro = estudiante2("Pedro", 99)
Pedro.presentarse()
There is one obvious difference, and that is when you use the base class name, as in
persona.__init__()
you have to passself
(the object being initialized) as the first argument. When you usesuper().__init__()
that argument instead, it is not set becausesuper()
it already returns the proper object that will be passed implicitly as the first parameter.But the real utility of
super()
is not saving that parameter, but not having to put "by hand" the name of the base class. Putting that name as part of the code can be a source of errors if, for example, you make a mistake when writing it or if, more commonly, you change the names of the classes later. If you make those name changes, you will have to edit and change all the places where you had put the base class name. Usingsuper()
there is no need to touch the code because itsuper()
automatically finds out the name of the base class.There are also differences in the case of multiple inheritance (a class inheriting from two or more classes). In that case
super()
it allows you to call a method of any of its base classes without needing to specify which of the base classes contains it (itsuper()
would look up which one it is). If two or more classes from which you inherit implement the same method, itsuper()
will invoke the method of the first one it finds, following the Method resolution order (MRO), which is usually the order in which the base classes were declared (although things can get complicated if these in turn inherited from others and there is "inheritance in diamond").An example of multiple inheritance:
Produces the output:
in which you can see that it found the method
susurrar()
orgritar()
in the base class that contained it, and that in the case of the method itsaludar()
used the method of class A because it appears before according to the MRO.By the way, you can find out that resolution order like this: