Skip to content
thesarfo

Concept

Inheritance in Python

Creating a subclass that inherits properties and methods from a parent class, illustrated with an ElectricCar extending Car.

views 0

A mechanism where a new class (child/subclass) is created by inheriting properties and methods from an existing class (parent/superclass).

class ElectricCar(Car): # Inherits from Car
def __init__(self, brand, model, battery_capacity):
super().__init__(brand, model)
self.battery_capacity = battery_capacity
def charge(self):
return f"Charging {self.brand} {self.model} with {self.battery_capacity} kWh"

Creating an electric car object:

electric_car = ElectricCar("Tesla", "Model S", 100)
print(electric_car.drive()) # Output: Driving Tesla Model S
print(electric_car.charge()) # Output: Charging Tesla Model S with 100 kWh