The super()
method is used to call a method from a parent class within a subclass. It allows us to access and invoke the methods and attributes of the parent class, enabling you to extend or override their behavior in the subclass.
Let's take an example of a Vehicle
class and a Car
subclass to understand how the super()
method works:
class Vehicle: def __init__(self, make, model): self.make = make self.model = model def start_engine(self): print("Engine started!") class Car(Vehicle): def __init__(self, make, model, color): super().__init__(make, model) self.color = color def start_engine(self): super().start_engine() print("Car engine started!") my_car = Car("Toyota", "Camry", "Blue") my_car.start_engine()
In this code, we define a Vehicle
class with an __init__
method and a start_engine
method. We also define a Car
subclass that inherits from the Vehicle
class.
In the Car
subclass, we override the __init__
method to add a color
attribute specific to cars. We use the super()
method in the __init__
method of the Car
class to call the __init__
method of the parent class (Vehicle
), ensuring that the make
and model
attributes are properly initialized.
We also override the start_engine
method in the Car
class to extend the behavior of the parent class. We use the super()
method to call the start_engine
method of the parent class (Vehicle
), and then print an additional message specific to cars.
When we create an object of the Car
class and call the start_engine
method, the super()
method allows us to invoke the start_engine
method of the parent class (Vehicle
) and extend its behavior in the subclass (Car
).
The output of the code will be:
Engine started!
Car engine started!
In this example, the super()
method enables us to leverage the functionality of the parent class while extending or customizing it in the subclass.
The super()
method is particularly useful when you want to invoke the methods of the parent class while adding or modifying functionality in the subclass.