Python

How is super used and what is it for in Python classes?

January 3, 2022

How is super used and what is it for in Python classes?

In this article you will learn how is super used in Python classes, and also the best pratices to use this statement.

How is super used cover

What’s up programmer, Are you okay? Let’s learn more about Python!

The “super” basically serves to access the methods of the parent class, for the class you are creating

We are faster by not having to type the class name explicitly

And it gives us the possibility to work with multiple inheritance

So let’s see the “super” in practice:

class Mamifero(object):
 def andar(self):
  print("O mamífero andou")

class Cachorro(Mamifero):
 def __init__(self):
  print('O cachorro nasceu.')
 def andar(self):
  super().andar() 

cachorro = Cachorro()

cachorro.rolar()

We created the parent class Mamifero, which would be the base class, and the derived class Dog

In the dog class we pass Mamifero as the base class in the arguments, and in the Dog walk method, we call  super the base class method, which is Mamifero

Now look at an example of multiple inheritance:

class Base1:
 def teste(self):
  print("Base 1")

class Base2:
 def testeB(self):
  print("Base 2")

class MultiHeranca(Base1, Base2):
 def herancaA(self):
  return super().teste()
 def herancaB(self):
  return super().testeB()

c1 = MultiHeranca()

c1.herancaA()

c1.herancaB()

The results in the code will be:

Base 1

Base 2

Methods that have been inherited from distinct base classes

We can use the super in favor of code maintainability, not having to repeat previously created methods

Simply taking advantage of methods from Base classes, referencing them in the same class

And if you need multiple methods, also opt for multiple inheritance that will solve your problem.

Another idea is that if several classes have similar methods, we can create a kind of super class containing these methods and even some variations

Conclusion

In this article, we’ve learned what super is for in Python classes

And also how we can use inheritance and multiple inheritance, from the super method

Although cases of multiple inheritance are rarer, it exists and is easily applicable

Want to learn more about Python? Click here!

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x