Python- Day 30- CLASSES-Inheritance
Inheritance allows a new class (called a “child class”) to use the features of an existing class (the “parent class”)
If you have a class that represents something specific based on a general idea (like an electric car based on a generic car), inheritance saves you from rewriting shared details.
The child class inherits the attributes (properties) and methods (actions) of the parent class but can also add its own unique features.
Example: Suppose we have a Car
class with some basic attributes and methods. We'll then create a ElectricCar
class that inherits from Car
.
# Parent class
class Car:
#A simple attempt to represent a car
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def get_descriptive_name(self):
#Return a neatly formatted descriptive name.
return f"{self.year} {self.make} {self.model}"
# Child class
class ElectricCar(Car):
def __init__(self, make, model, year):
super().__init__(make, model, year) # Calls __init__ from Car
# Creating an instance of ElectricCar
my_tesla = ElectricCar('Tesla', 'Model S', 2024)
print(my_tesla.get_descriptive_name())
>>
Output: "2024 Tesla Model S"
In the above example:
ElectricCar
inherits from Car
, so it has access to Car
's attributes and methods.
super().__init__(make, model, year)
initializes the inherited attributes from Car
in ElectricCar
.
Car
class:
class Car:
"""A simple representation of a car."""
def __init__(self, make, model, year):
"""Initialize the attributes of the car."""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""Return a nicely formatted descriptive name for the car."""
long_name = f"{self.year} {self.make} {self.model}"
return long_name.title()
def read_odometer(self):
"""Print the car's mileage."""
print(f"This car has {self.odometer_reading} miles on it.")
Creating a Child Class with Inheritance:
Now we want to create an ElectricCar
class that inherits from Car
and adds electric car-specific details.
class ElectricCar(Car):
#Represent aspects of a car, specific to electric vehicles.
def __init__(self, make, model, year):
"""
Initialize the parent class's attributes.
Then initialize attributes specific to an electric car.
"""
super().__init__(make, model, year) # Initialize the parent class
self.battery_size = 40 # Attribute specific to electric cars
def describe_battery(self):
#Print a statement about the battery size.
print(f"This car has a {self.battery_size}-kWh battery.")
super(): The super()
function calls the __init__
method of the parent class to initialize its attributes.
Using the Child Class:
Now let’s create an instance of ElectricCar
and use its methods.
my_leaf = ElectricCar('nissan', 'leaf', 2024)
print(my_leaf.get_descriptive_name()) # Inherited method
my_leaf.describe_battery() # Method unique to ElectricCar
>>
2024 Nissan Leaf
This car has a 40-kWh battery.
Overriding Parent Class Methods:
The child class can override any method in the parent class if needed.
For instance, if Car
had a fill_gas_tank
method, we could override it in ElectricCar
to indicate that electric cars don’t have gas tanks.
class ElectricCar(Car):
# Previous code here...
def fill_gas_tank(self):
"""Electric cars don't have gas tanks."""
print("This car doesn't have a gas tank!")
Composition: Using Instances as Attributes:
As our ElectricCar
grows in detail, we might want to separate the Battery
details into its own class, rather than adding everything directly to ElectricCar
.
class Car:
#A simple representation of a car.
def __init__(self, make, model, year):
#Initialize the attributes of the car.
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
#Return a nicely formatted descriptive name for the car.
long_name = f"{self.year} {self.make} {self.model}"
return long_name.title()
def read_odometer(self):
#Print the car's mileage.
print(f"This car has {self.odometer_reading} miles on it.")
class ElectricCar(Car):
#Represent aspects of a car, specific to electric vehicles.
def __init__(self, make, model, year):
"""
Initialize the parent class's attributes.
Then initialize attributes specific to an electric car.
"""
super().__init__(make, model, year) # Initialize the parent class
self.battery_size = 40 # Attribute specific to electric cars
def describe_battery(self):
#Print a statement about the battery size.
print(f"This car has a {self.battery_size}-kWh battery.")
class Battery:
#A simple representation of an electric car's battery.
def __init__(self, battery_size=40):
#Initialize the battery's attributes.
self.battery_size = battery_size
def describe_battery(self):
#Print a statement describing the battery size.
print(f"This car has a {self.battery_size}-kWh battery.")
def get_range(self):
#Print the range based on battery size.
if self.battery_size == 40:
range = 150
elif self.battery_size == 65:
range = 225
print(f"This car can go about {range} miles on a full charge.")
class ElectricCar(Car):
def __init__(self, make, model, year):
#Initialize the attributes of the parent class and battery.
super().__init__(make, model, year)
self.battery = Battery() # Adding a Battery instance
my_leaf = ElectricCar('nissan', 'leaf', 2024)
print(my_leaf.get_descriptive_name())
my_leaf.battery.describe_battery()
my_leaf.battery.get_range()
>>
2024 Nissan Leaf
This car has a 40-kWh battery.
This car can go about 150 miles on a full charge.
Inheritance lets you build new classes by reusing code from existing ones.
super() allows a child class to call the parent class’s methods.
Overriding methods enables customization of inherited behavior.
Composition lets you break down complex classes into smaller parts by using instances as attributes.
If you found this guide helpful then do click on 👏 the button.
Follow for more Learning like this 😊
If there’s a specific topic you’re curious about, feel free to drop a personal note or comment. I’m here to help you explore whatever interests you!