34. Problem to create an inheritance real life example in Python

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
  1. 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.
  2. The class also has a print_details method that prints the make, model, and year of the car.
  3. 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.
  4. 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.
  5. The calculate_range method calculates the range of the electric car based on the battery size and range per charge.
  6. 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.
  7. The calculate_range method is called on the electric_car object, which calculates the range of the electric car.
  8. The calculated range is stored in the variable range and printed.
  9. 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 Car with attributes make, model, and year.

Create a Python class called StudentRecord with attributes name, age, and grades.

Leave a Comment