Curriculum
super()
is a built-in function in Python that allows you to call a method in a superclass from a subclass. It’s often used in object-oriented programming when you want to override a method in a subclass but still call the superclass’s implementation of that method.
Here’s an example to illustrate how super()
works:
class Vehicle: def __init__(self, brand, model): self.brand = brand self.model = model def drive(self): print(f"{self.brand} {self.model} is driving") class Car(Vehicle): def __init__(self, brand, model, num_wheels): super().__init__(brand, model) self.num_wheels = num_wheels def drive(self): super().drive() print(f"{self.brand} {self.model} is driving on {self.num_wheels} wheels")
In this example, we have a superclass called Vehicle
that has an __init__
method to initialize the brand
and model
attributes of the vehicle, as well as a drive
method to print a message that the vehicle is driving.
We also have a subclass called Car
that inherits from Vehicle
and adds a num_wheels
attribute to represent the number of wheels on the car. The __init__
method of the Car
class uses super()
to call the __init__
method of the Vehicle
class to initialize the brand
and model
attributes.
The drive
method of the Car
class overrides the drive
method of the Vehicle
class to add a message about the number of wheels on the car. However, it also uses super()
to call the drive
method of the Vehicle
class to print the message that the car is driving.
Here’s an example of how you can use these classes:
my_car = Car("Toyota", "Camry", 4) my_car.drive()
This will output the following message:
Toyota Camry is driving Toyota Camry is driving on 4 wheels
As you can see, the drive
method of the Car
class first calls super().drive()
to print the message that the car is driving, and then adds a message about the number of wheels on the car. This allows the Car
class to add specialized behavior to the drive
method while still using the implementation of the Vehicle
class.