Python Inheritance
Inheritance allows us to define a class that inherits all the methods and properties from another class. The parent class is known as the base class, and the child class is known as the derived class.
Example 1: Single Inheritance
Create a base class Person
and a derived class Student
.
# Single inheritance
class Person:
def __init__(self, name):
self.name = name
def display_name(self):
print("Name:", self.name)
class Student(Person):
def study(self):
print(f"{self.name} is studying.")
student = Student("Riya")
student.display_name()
student.study()
Name: Riya
Riya is studying.
Example 2: Multilevel Inheritance
Create a class hierarchy where Animal
is the base class, Mammal
inherits from Animal
, and Dog
inherits from Mammal
.
# Multilevel inheritance
class Animal:
def eat(self):
print("Eating")
class Mammal(Animal):
def walk(self):
print("Walking")
class Dog(Mammal):
def bark(self):
print("Barking")
dog = Dog()
dog.eat()
dog.walk()
dog.bark()
Eating
Walking
Barking
Example 3: Multiple Inheritance
Create a class Employee
that inherits from both Person
and Worker
.
# Multiple inheritance
class Person:
def __init__(self, name):
self.name = name
class Worker:
def work(self):
print(f"{self.name} is working.")
class Employee(Person, Worker):
def __init__(self, name, position):
Person.__init__(self, name)
self.position = position
def show_position(self):
print(f"Position: {self.position}")
employee = Employee("Tamilmaran", "Engineer")
employee.show_position()
employee.work()
Position: Engineer
Tamilmaran is working.
Example 4: Overriding Methods
Override a method in the child class.
# Method overriding
class Vehicle:
def start(self):
print("Starting the vehicle")
class Car(Vehicle):
def start(self):
print("Starting the car")
car = Car()
car.start()
Starting the car
Example 5: Using super()
Function
Call the parent class method using super()
.
# Using super()
class Parent:
def greet(self):
print("Hello from Parent")
class Child(Parent):
def greet(self):
super().greet()
print("Hello from Child")
child = Child()
child.greet()
Hello from Parent
Hello from Child
Example 6: Hierarchical Inheritance
Create multiple classes inheriting from a single base class.
# Hierarchical inheritance
class Fruit:
def info(self):
print("This is a fruit.")
class Apple(Fruit):
def taste(self):
print("Apples are sweet.")
class Orange(Fruit):
def taste(self):
print("Oranges are citrus.")
apple = Apple()
orange = Orange()
apple.info()
apple.taste()
orange.info()
orange.taste()
This is a fruit.
Apples are sweet.
This is a fruit.
Oranges are citrus.
Explanation: Inheritance allows for code reusability and logical hierarchy. Overriding methods and using super()
help manage method resolution in inheritance hierarchies.