Login Register

What Is Inheritance In Python?

What Is Inheritance?

Python inheritance is like a supply chain that allows one class to use the properties and methods of another class without rewriting the same code again.

It describes the parent-child combination. It means a child gets eye color, habits, or skills from parents, similar a Python class can get variables and functions from another class.

Why Is Inheritance Useful In Python?

  • It reduces to writing the same code multiple times.
  • Helping us to organize large programs for big projects.
  • It is best in the code updating process, just a change in one place affects all subclasses.
  • Also allows new classes to extend or modify old classes.

How To Define Inheritance In Python?

Here we are creating a new class (child class) that automatically receives the properties and methods of another class (parent class).

Syntax of inheritance:

class ParentClass:
# Parent class properties and methods

class ChildClass(ParentClass):
# Child class content (inherits everything from ParentClass)
  • ChildClass should reuse whatever is inside ParentClass.
  • You can also add new methods or override parent methods.

Example of Inheritance

This code describes basic inheritance (child extends parent): Vehicle → Bike

class Vehicle:
def info(self):
return "This is a general vehicle."

class Bike(Vehicle):
def wheels(self):
return "This bike has 2 wheels."

b = Bike()
print(b.info()) # Inherited from Vehicle
print(b.wheels()) # Method defined inside Bike

Code Output:

This is a general vehicle.
This bike has 2 wheels.

Meaning of the code:

  • Bike gets the info() method because it inherits from Vehicle.
  • The child class also has an extra method wheels().

Example 2: Method Overriding (Child Changes Parent Behavior):

Notification → EmailNotification

class Notification:
def send(self):
return "Sending a general notification..."

class EmailNotification(Notification):
def send(self): # Overriding the parent method
return "Sending notification through Email."

n = Notification()
print(n.send())

e = EmailNotification()
print(e.send())

Output:

Sending a general notification...
Sending notification through Email.

Explanation:

  • Notification has a sand() method.
  • The child class EmailNotification overrides it and provides its own version.
  • So when we call send() on the child object, Python uses the child’s version.

Accessing Parent Class Methods

When a child class creates its own version of a method that already exists in the parent class, the parent’s method gets replaced.

In this case, Python provides the super() function, because super() allows the child class to call the parent class method without the parent class name again.

Example: Course → PythonCourse

class Course:
def details(self):
print("This is a general course.")

class PythonCourse(Course):
def details(self):
super().details() # Calling method of parent class
print("This course teaches Python programming.")

p = PythonCourse()
p.details()

Output:

This is a general course.
This course teaches Python programming.

Explanation of the code:

  • Course is the parent class.
  • PythonCourse overrides the details() method.
  • But before running its own message, it uses super().details() to run the parent’s version.
  • The result is combined output from both classes.

So, super() helps you extend the parent’s functionality instead of replacing it.

Types of Inheritance in Python

Python supports 5 types of inheritance.

  • Single Inheritance
  • Multiple Inheritance
  • Multilevel Inheritance
  • Hierarchical Inheritance
  • Hybrid Inheritance

1) Single Inheritance

  • Single inheritance means a child class is created from only one parent class.
  • The child automatically gets the parent’s features, similar to child gets habits from a single parent.

For Example, A parent class records how many steps a person walks. And a child class uses that information to calculate calories burned.

class StepTracker:
def set_steps(self, steps):
self.steps = steps

def get_steps(self):
return self.steps

class CalorieCalculator(StepTracker):
def calories_burned(self):
# unique logic: assume 0.04 calories per step
return self.steps * 0.04

# Using the classes
person = CalorieCalculator()
person.set_steps(3000)

print("Steps Walked:", person.get_steps())
print("Calories Burned:", person.calories_burned())

Output:

Steps Walked: 3000
Calories Burned: 120.0

2) Multiple Inheritance

  • Multiple inheritance means a single child class can receive features (methods + variables) from multiple parent classes.
  • For example, you learn discipline from your father and learn creativity from your mother.

For example, A robot gets abilities from two separate parent classes: One parent gives speaking ability, and the second parent gives movement ability

class MovementSystem:
def move(self):
return "Moving forward using wheels"

class VoiceSystem:
def speak(self):
return "Speaking: 'Hello! I am Robo-X.'"

class SmartRobot(MovementSystem, VoiceSystem):
pass

# Creating object of child class
robot = SmartRobot()

print(robot.move()) # From MovementSystem
print(robot.speak()) # From VoiceSystem

Final output of this code:

Moving forward using wheels
Speaking: 'Hello! I am Robo-X.'

3) Multilevel Inheritance

  • Multilevel inheritance means one class inherits from another, and then another class inherits from that second class.
  • Imagine, it’s like a family chain, where Grandparent → Parent → Child inherits data.

Example: Message Builder Through Generations

class BaseMessage:
def step_one(self):
return "Hello"

class MidMessage(BaseMessage):
def step_two(self):
part1 = self.step_one()
return part1 + ", how are you"

class FinalMessage(MidMessage):
def step_three(self):
part2 = self.step_two()
return part2 + " today?"

msg = FinalMessage()
print(msg.step_three())

Output of the multilevel inheritance:

Hello, how are you today?

4) Hierarchical Inheritance

Hierarchical means multiple child classes inherit from a single parent class. Each child can use the parent’s attributes and methods, but they can also have their own unique features.

This type is used to avoid code duplication and is useful when you have different types of objects that share common behavior.

Hierarchical Inheritance Example: We have a parent class Vehicle with a method start(). Two child classes, Car and Bicycle, inherit from Vehicle and have their own specific methods.

# Parent class
class Vehicle:
def start(self):
return "Vehicle is starting."

# Child class 1
class Car(Vehicle):
def wheels(self):
return "I have 4 wheels."

# Child class 2
class Bicycle(Vehicle):
def wheels(self):
return "I have 2 wheels."

# Creating objects
car = Car()
bike = Bicycle()

print(car.start()) # Outputs: Vehicle is starting.
print(car.wheels()) # Outputs: I have 4 wheels.

print(bike.start()) # Outputs: Vehicle is starting.
print(bike.wheels()) # Outputs: I have 2 wheels.

Output:

Vehicle is starting.
I have 4 wheels.

Vehicle is starting.
I have 2 wheels.

5) Hybrid Inheritance

In this type a single, multiple, or multilevel inheritance works into a single structure.

Example: Suppose we have a Device class.

  • Two classes, Computer and Phone, inherit from Device.
  • Then a SmartDevice inherits from both Computer and Phone to combine features.
# Base class
class Device:
def power_on(self):
return "Device is powered on."

# First level child 1
class Computer(Device):
def compute(self):
return "I can run software programs."

# First level child 2
class Phone(Device):
def call(self):
return "I can make phone calls."

# Hybrid child combining both
class SmartDevice(Computer, Phone):
def browse_internet(self):
return "I can browse the internet."

# Creating object
smart_gadget = SmartDevice()

# Accessing methods
print(smart_gadget.power_on()) # From Device
print(smart_gadget.compute()) # From Computer
print(smart_gadget.call()) # From Phone
print(smart_gadget.browse_internet()) # Unique to SmartDevice

Explanation:

Device is powered on.
I can run software programs.
I can make phone calls.
I can browse the internet.