Python Inheritance
Learn how one Python class can inherit attributes and methods from another class, how child classes extend parent classes, and how inheritance helps you build reusable and organized applications.
Learning Objectives
In the previous two lessons, you learned how to create classes, objects, attributes, methods, and constructors.
Now we will learn how classes can build upon other classes.
By the end of this lesson, you will be able to:
- Understand inheritance in Python.
- Identify parent and child classes.
- Create a child class from a parent class.
- Reuse inherited methods and attributes.
- Add new functionality to child classes.
- Override inherited methods.
- Use
super(). - Understand different inheritance patterns.
- Use
isinstance()andissubclass(). - Design practical inheritance hierarchies.
What Is Inheritance?
Inheritance is an object-oriented programming feature that allows one class to acquire attributes and methods from another class.
The class that provides the functionality is commonly called the parent class, base class, or superclass.
The class that inherits from it is commonly called the child class, derived class, or subclass.
Simple idea
Instead of writing the same code again in several classes, create common functionality once in a parent class and allow related child classes to reuse it.
Why Use Inheritance?
Imagine an application that manages different types of employees.
Every employee may have a name, department, and salary. But different employee types may have additional responsibilities.
Employee
│
├── Manager
│
├── Developer
│
└── SalesPerson
The common employee functionality can live in
Employee, while specialized behavior can be
added to the child classes.
Main benefits
- Code reuse
- Reduced duplication
- Better organization
- Specialized child classes
- Easier maintenance
Parent and Child Classes
Let's define a simple parent class and a child class.
class Animal:
pass
class Dog(Animal):
pass
Here, Animal is the parent class and
Dog is the child class.
Animal
↓
Dog
The syntax inside the parentheses tells Python that
Dog inherits from Animal.
Basic Inheritance
Let's create a useful example.
class Animal:
def eat(self):
print("The animal is eating.")
class Dog(Animal):
pass
dog = Dog()
dog.eat()
The animal is eating.
We did not define eat() inside
Dog, but the dog can still use it because
the method is inherited from Animal.
Inherited Methods
A child class automatically has access to accessible methods defined by its parent class.
class Vehicle:
def start(self):
print("Vehicle started.")
def stop(self):
print("Vehicle stopped.")
class Car(Vehicle):
pass
car = Car()
car.start()
car.stop()
Vehicle started.
Vehicle stopped.
The Car class reuses both methods without
rewriting them.
Inherited Attributes
A child class can also use attributes initialized by a parent class.
class Person:
def __init__(self, name):
self.name = name
class Student(Person):
pass
student = Student("Ali")
print(student.name)
Ali
Because Student inherits from
Person, its objects can use the parent's
constructor when the child does not define its own
constructor.
Adding Features to a Child Class
Inheritance is not only about reusing code. A child class can also add its own attributes and methods.
class Animal:
def eat(self):
print("Eating...")
class Dog(Animal):
def bark(self):
print("Woof!")
dog = Dog()
dog.eat()
dog.bark()
Eating...
Woof!
Dog has both the inherited
eat() method and its own
bark() method.
Method Overriding
Sometimes a child class needs to provide a different implementation of a method inherited from its parent.
This is called method overriding.
class Animal:
def make_sound(self):
print("Some animal sound.")
class Dog(Animal):
def make_sound(self):
print("Woof!")
dog = Dog()
dog.make_sound()
Woof!
Python uses the child class's implementation when the overridden method is called on a child object.
Important
Overriding does not delete the parent method. The child simply provides its own implementation for calls made through that child class.
The super() Function
The super() function gives a child class a
convenient way to access functionality from its parent
class.
This is particularly useful when a child overrides a method but still wants to use part of the parent's implementation.
class Animal:
def make_sound(self):
print("Animal makes a sound.")
class Dog(Animal):
def make_sound(self):
super().make_sound()
print("Dog says Woof!")
dog = Dog()
dog.make_sound()
Animal makes a sound.
Dog says Woof!
Here, super().make_sound() calls the parent
class implementation before the child adds its own
behavior.
super() with __init__()
One of the most common uses of super() is
calling the parent constructor.
class Person:
def __init__(self, name):
self.name = name
class Student(Person):
def __init__(self, name, course):
super().__init__(name)
self.course = course
student = Student("Ali", "Python")
print(student.name)
print(student.course)
Ali
Python
The child constructor initializes its own
course attribute while
super().__init__(name) lets the parent
initialize name.
Why this is useful
It prevents you from duplicating the parent's initialization logic in the child class.
Multilevel Inheritance
In multilevel inheritance, a class inherits from another child class.
Animal
↓
Mammal
↓
Dog
class Animal:
def eat(self):
print("Eating...")
class Mammal(Animal):
def breathe(self):
print("Breathing...")
class Dog(Mammal):
def bark(self):
print("Woof!")
dog = Dog()
dog.eat()
dog.breathe()
dog.bark()
Eating...
Breathing...
Woof!
The Dog object can access behavior inherited
through the entire inheritance chain.
Multiple Inheritance
Python allows a class to inherit from more than one parent class.
class Camera:
def take_photo(self):
print("Taking photo.")
class Phone:
def make_call(self):
print("Making call.")
class Smartphone(Camera, Phone):
pass
phone = Smartphone()
phone.take_photo()
phone.make_call()
Taking photo.
Making call.
Use multiple inheritance carefully
Multiple inheritance is powerful, but complex inheritance hierarchies can become difficult to understand. Prefer simple and clear designs when possible.
Hierarchical Inheritance
In hierarchical inheritance, multiple child classes inherit from the same parent class.
Employee
/ \
/ \
Developer Manager
class Employee:
def login(self):
print("Employee logged in.")
class Developer(Employee):
def code(self):
print("Writing code.")
class Manager(Employee):
def manage(self):
print("Managing team.")
developer = Developer()
manager = Manager()
developer.login()
developer.code()
manager.login()
manager.manage()
Using isinstance()
The built-in isinstance() function checks
whether an object is an instance of a particular class
or a class derived from it.
class Animal:
pass
class Dog(Animal):
pass
dog = Dog()
print(isinstance(dog, Dog))
print(isinstance(dog, Animal))
True
True
The second result is also True because a
Dog is also an instance of its parent
Animal.
Using issubclass()
The issubclass() function checks whether one
class inherits from another class.
class Animal:
pass
class Dog(Animal):
pass
print(issubclass(Dog, Animal))
print(issubclass(Animal, Dog))
True
False
isinstance() works with objects,
while issubclass() works with
classes.
Real-World Inheritance Examples
Inheritance is especially useful when several entities share common behavior but also have specialized features.
Example 1 — Ecommerce Products
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def show_details(self):
print(self.name)
print(self.price)
class PhysicalProduct(Product):
def calculate_shipping(self):
print("Shipping required.")
class DigitalProduct(Product):
def download(self):
print("Download available.")
laptop = PhysicalProduct("Laptop", 85000)
ebook = DigitalProduct("Python Course", 5000)
laptop.show_details()
laptop.calculate_shipping()
ebook.show_details()
ebook.download()
Both product types reuse the common product structure, while each type adds its own specialized behavior.
Example 2 — Employees
class Employee:
def __init__(self, name):
self.name = name
def show_name(self):
print("Employee:", self.name)
class Developer(Employee):
def write_code(self):
print(self.name, "is writing code.")
class Manager(Employee):
def manage_team(self):
print(self.name, "is managing the team.")
developer = Developer("Ali")
manager = Manager("Sara")
developer.show_name()
developer.write_code()
manager.show_name()
manager.manage_team()
Example 3 — Vehicles
class Vehicle:
def __init__(self, brand):
self.brand = brand
def show_brand(self):
print("Brand:", self.brand)
class Car(Vehicle):
def drive(self):
print("Car is driving.")
class Bike(Vehicle):
def ride(self):
print("Bike is riding.")
car = Car("Toyota")
bike = Bike("Honda")
car.show_brand()
car.drive()
bike.show_brand()
bike.ride()
The design principle
Put common behavior in the parent class and specialized behavior in the child classes.
Common Inheritance Mistakes
1. Forgetting the parent class
# Inheritance
class Dog(Animal):
pass
The parent class is specified inside the parentheses.
2. Forgetting super()
If a child defines its own __init__(), the
parent's constructor does not automatically run just
because the child inherits from the parent.
class Person:
def __init__(self, name):
self.name = name
class Student(Person):
def __init__(self, name, course):
super().__init__(name)
self.course = course
3. Duplicating parent code
If the parent already provides reusable behavior,
avoid copying the same implementation into every
child class. Reuse it through inheritance or
super() where appropriate.
4. Creating overly complicated hierarchies
Inheritance should make the design clearer, not more confusing.
If the relationship between two classes is not a genuine "is-a" relationship, inheritance may not be the right design.
5. Confusing inheritance with composition
Inheritance generally represents an "is-a" relationship.
For example, a Dog is an Animal.
Composition generally represents a "has-a" relationship.
For example, a Car has an Engine.
Practice Exercises
Exercise 1 — Animal and Dog
Create an Animal class with an
eat() method. Create a Dog
class that inherits from it.
Exercise 2 — Vehicle
Create a Vehicle class with
start() and stop() methods.
Create a Car child class.
Exercise 3 — Method Overriding
Create a parent Animal class with
make_sound(). Override it inside
Dog and Cat.
Exercise 4 — super()
Create a Person class with a constructor.
Create a Student child class and use
super() to initialize the parent's data.
Exercise 5 — Multilevel Inheritance
Create an inheritance chain:
Animal → Mammal → Dog.
Give each class its own method.
Exercise 6 — Multiple Inheritance
Create Camera and Phone
classes and make a Smartphone class
inherit from both.
Exercise 7 — isinstance()
Create a parent and child class and use
isinstance() to test the child object
against both classes.
Exercise 8 — issubclass()
Use issubclass() to check whether your
child class inherits from the parent class.
Mini Challenge — Ecommerce Product System
Let's build a practical inheritance hierarchy for an ecommerce platform.
Your Mission
Build a product system containing a general
Product class and specialized product
types.
Requirements
- Create a
Productparent class. - Use a constructor for name and price.
- Create a
show_details()method. - Create a
PhysicalProductchild class. - Create a
DigitalProductchild class. - Give physical products a shipping method.
- Give digital products a download method.
- Create objects from both child classes.
- Use inherited and specialized methods.
Starter Code
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def show_details(self):
print("Name:", self.name)
print("Price:", self.price)
class PhysicalProduct(Product):
def shipping(self):
print("Shipping required.")
class DigitalProduct(Product):
def download(self):
print("Download available.")
laptop = PhysicalProduct("Laptop", 85000)
course = DigitalProduct("Python Course", 5000)
laptop.show_details()
laptop.shipping()
course.show_details()
course.download()
Extension Challenge
Add a stock attribute to physical products
and an is_available() method that determines
whether the product is currently available.
Developer thinking
Ask yourself which properties belong to every product and which properties are specific to physical or digital products.
Quick Knowledge Check
Test your understanding of Python inheritance.
1. What is inheritance?
2. What is the parent class?
3. Which syntax creates a child class?
4. What does method overriding mean?
5. What is super() commonly used for?
6. What does super().__init__() commonly do?
7. What does isinstance() check?
8. What does issubclass() check?
9. Which relationship usually represents inheritance?
10. Can Python support multiple inheritance?
Lesson Summary
Inheritance allows Python classes to build upon existing classes instead of repeatedly writing the same functionality.
Key Takeaways
- Inheritance allows one class to reuse another class's functionality.
- The parent class provides reusable behavior.
- The child class can inherit and extend that behavior.
- Child classes can add their own attributes and methods.
- Method overriding allows specialized behavior.
-
super()provides access to parent functionality. -
super().__init__()is commonly used to initialize the parent portion of an object. - Python supports multilevel, hierarchical, and multiple inheritance.
-
isinstance()checks objects. -
issubclass()checks class relationships.
What's next?
In the next lesson, we will explore Polymorphism — the ability to use a common interface while allowing different classes to provide different implementations.
Ready for the next step?
Complete this lesson once you are comfortable with parent
classes, child classes, overriding, and
super().