Python Inheritance is a mechanism in object-oriented programming (OOP) that allows a new class to be defined by inheriting properties and methods from an existing class. The existing class is called the base class or the parent class, and the new class is called the derived class or the child class.
Inheritance enables code reuse and promotes the DRY (Don’t Repeat Yourself) principle in programming. By inheriting from a base class, a derived class can inherit the attributes and behaviors of the base class, and can also add new attributes and behaviors of its own.
In python, you can use the class DerivedClassName(BaseClassName)
syntax to create a derived class that inherits from a base class. The base class is specified in the parentheses after the derived class name.
For example, you have a base class Animal
and you want to create a derived class Dogs
that inherits from Animals
you would do this:
class Animals:
def __init__(self, name, species):
self.name = name
self.species = species
def speak(self):
print("I am an animal!")
class Dogs(Animals):
def __init__(self, name, breed):
super().__init__(name, species="Dog")
self.breed = breed
def bark(self):
print("Woof woof!")
dog1 = Dogs("Max", "Golden Retriever")
dog1.speak() #I am an animal!
dog1.bark() #Woof woof!
I am an animal!
Woof woof!
In this example, the Dogs
class inherits from the Animals
class and inherits the speak()
method, it also has its own method bark()
and a constructor that calls the constructor of the base class using the super()
method.
It’s worth mentioning that Python supports multiple inheritance, where a class can inherit from more than one base class.
Let consider some more Examples
1. Creating a shape class hierarchy:
class Shape:
def __init__(self, sides):
self.sides = sides
def area(self):
pass
class Square(Shape):
def __init__(self, length):
super().__init__(4)
self.length = length
def area(self):
return self.length ** 2
class Triangle(Shape):
def __init__(self, base, height):
super().__init__(3)
self.base = base
self.height = height
def area(self):
return 0.5 * self.base * self.height
sq = Square(5)
print(sq.area()) # 25
tri = Triangle(5, 10)
print(tri.area()) # 25
25
25.0
In this example, we have a base class Shape
with a constructor that takes the number of sides and an area()
method that is not implemented. We created two derived classes Square
and Triangle
that both inherit from the Shape
class, the Square
class has a constructor that takes the length of its sides and calculates the area by squaring the length, the Triangle
class has a constructor that takes the base and the height of the triangle and calculates the area using the base and the height.
2. Creating a vehicle class hierarchy:
class Vehicle:
def __init__(self, make, model):
self.make = make
self.model = model
def drive(self):
print("The vehicle is driving.")
class Car(Vehicle):
def __init__(self, make, model, year):
super().__init__(make, model)
self.year = year
def honk(self):
print("Beep beep!")
class Truck(Vehicle):
def __init__(self, make, model, payload_capacity):
super().__init__(make, model)
self.payload_capacity = payload_capacity
def drive(self):
print("The truck is hauling cargo.")
car = Car("Toyota", "Camry", 2022)
car.drive() #The vehicle is driving.
car.honk() #Beep beep!
truck = Truck("Ford", "F-150", 1000)
truck.drive() #The truck is hauling cargo.
The vehicle is driving.
Beep beep!
The truck is hauling cargo.
In this example, we have a base class Vehicle
with a constructor that takes the make and model of the vehicle and a drive method that prints “The vehicle is driving.” We created two derived classes Car
and Truck
that both inherit from the Vehicle
class, the Car
class has a constructor that takes the make, model, and year of the car and has a honk method that prints “Beep beep!”, the Truck
class has a constructor that takes the make, model, and payload capacity of the truck and overrides the drive method to print “The truck is hauling cargo.”
In both examples, the derived classes inherit the properties and methods from the base class, and in the second example, the derived class overrides the method of the base class.