Junior — Middle
Can you explain what the use of the keyword super() means in Python?
sobes.tech AI
Answer from AI
In Python, the keyword super() is used to call methods of a parent (base) class from a child class. This is especially useful when overriding methods, as it allows you to extend the behavior of the base class rather than completely replacing it.
super() returns an object that delegates method calls to the parent class, enabling you to call, for example, the constructor or other methods of the base class.
Example:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound")
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # call to the base class constructor
self.breed = breed
def speak(self):
super().speak() # call to the base class method
print(f"{self.name} barks")
my_dog = Dog("Sharik", "shepherd")
my_dog.speak()
Output:
Sharik makes a sound
Sharik barks
Thus, super() helps avoid explicitly specifying the name of the base class and makes the code more flexible and maintainable, especially in multiple inheritance.