In this Python oops program, we will create an inheritance real life example in Python. Python class called ElectricCar that inherits from the Car class.
Inheritance real life example
Steps to solve the program
- The Car class represents a general car and has a constructor method __init__ that takes three parameters: make, model, and year. It initializes the instance variables self.make, self.model, and self.year with the provided values.
- The class also has a print_details method that prints the make, model, and year of the car.
- The ElectricCar class is a subclass of Car and represents an electric car. It extends the Car class by adding two additional attributes: battery_size and range_per_charge.
- The __init__ method of the ElectricCar class takes the same parameters as the Car class, as well as the new attributes specific to electric cars. It calls the superclass’s (Car) __init__ method using super() to initialize the inherited attributes.
- The calculate_range method calculates the range of the electric car based on the battery size and range per charge.
- The code creates an object electric_car of the ElectricCar class with the make “Tesla”, model “Model S”, year 2022, battery size 75, and range per charge 5.
- The calculate_range method is called on the electric_car object, which calculates the range of the electric car.
- The calculated range is stored in the variable range and printed.
- Thus, we have created an inheritance real life example.
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def print_details(self):
print("Make:", self.make)
print("Model:", self.model)
print("Year:", self.year)
class ElectricCar(Car):
def __init__(self, make, model, year, battery_size, range_per_charge):
super().__init__(make, model, year)
self.battery_size = battery_size
self.range_per_charge = range_per_charge
def calculate_range(self):
return self.battery_size * self.range_per_charge
# Create an object of the ElectricCar class
electric_car = ElectricCar("Tesla", "Model S", 2022, 75, 5)
range = electric_car.calculate_range()
print("Range:", range)
Output:
Range: 375
Related Articles
Create a Python class called StudentRecord with attributes name, age, and grades.
Create a Python class called Course with attributes name, teacher, and students.
Create a Python class called Shape with a method to calculate the area of the shape.
Create a Python class called Employee with attributes name and salary.
Create a Python class called Manager that inherits from the Employee class.
Create a Python class called Customer with attributes name and balance.