PyLearn Object-Oriented Programming Python Inheritance
Lesson 45 Object-Oriented Programming

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.

50–60 minutes Intermediate Object-Oriented Programming
0%
01

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() and issubclass().
  • Design practical inheritance hierarchies.
02

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.

03

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.

Possible Structure
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
04

Parent and Child Classes

Let's define a simple parent class and a child class.

Python
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.

05

Basic Inheritance

Let's create a useful example.

Python
class Animal:

    def eat(self):
        print("The animal is eating.")


class Dog(Animal):
    pass


dog = Dog()

dog.eat()
Output
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.

06

Inherited Methods

A child class automatically has access to accessible methods defined by its parent class.

Python
class Vehicle:

    def start(self):
        print("Vehicle started.")

    def stop(self):
        print("Vehicle stopped.")


class Car(Vehicle):
    pass


car = Car()

car.start()
car.stop()
Output
Vehicle started.
Vehicle stopped.

The Car class reuses both methods without rewriting them.

07

Inherited Attributes

A child class can also use attributes initialized by a parent class.

Python
class Person:

    def __init__(self, name):
        self.name = name


class Student(Person):
    pass


student = Student("Ali")

print(student.name)
Output
Ali

Because Student inherits from Person, its objects can use the parent's constructor when the child does not define its own constructor.

08

Adding Features to a Child Class

Inheritance is not only about reusing code. A child class can also add its own attributes and methods.

Python
class Animal:

    def eat(self):
        print("Eating...")


class Dog(Animal):

    def bark(self):
        print("Woof!")


dog = Dog()

dog.eat()
dog.bark()
Output
Eating...
Woof!

Dog has both the inherited eat() method and its own bark() method.

09

Method Overriding

Sometimes a child class needs to provide a different implementation of a method inherited from its parent.

This is called method overriding.

Python
class Animal:

    def make_sound(self):
        print("Some animal sound.")


class Dog(Animal):

    def make_sound(self):
        print("Woof!")


dog = Dog()

dog.make_sound()
Output
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.

10

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.

Python
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()
Output
Animal makes a sound.
Dog says Woof!

Here, super().make_sound() calls the parent class implementation before the child adds its own behavior.

11

super() with __init__()

One of the most common uses of super() is calling the parent constructor.

Python
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)
Output
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.

12

Multilevel Inheritance

In multilevel inheritance, a class inherits from another child class.

Structure
Animal
   ↓
Mammal
   ↓
Dog
Python
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()
Output
Eating...
Breathing...
Woof!

The Dog object can access behavior inherited through the entire inheritance chain.

13

Multiple Inheritance

Python allows a class to inherit from more than one parent class.

Python
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()
Output
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.

14

Hierarchical Inheritance

In hierarchical inheritance, multiple child classes inherit from the same parent class.

Structure
        Employee
        /      \
       /        \
Developer      Manager
Python
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()
15

Using isinstance()

The built-in isinstance() function checks whether an object is an instance of a particular class or a class derived from it.

Python
class Animal:
    pass


class Dog(Animal):
    pass


dog = Dog()

print(isinstance(dog, Dog))
print(isinstance(dog, Animal))
Output
True
True

The second result is also True because a Dog is also an instance of its parent Animal.

16

Using issubclass()

The issubclass() function checks whether one class inherits from another class.

Python
class Animal:
    pass


class Dog(Animal):
    pass


print(issubclass(Dog, Animal))
print(issubclass(Animal, Dog))
Output
True
False

isinstance() works with objects, while issubclass() works with classes.

17

Real-World Inheritance Examples

Inheritance is especially useful when several entities share common behavior but also have specialized features.

Example 1 — Ecommerce Products

Python
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

Python
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

Python
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.

18

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.

19

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.

20

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 Product parent class.
  • Use a constructor for name and price.
  • Create a show_details() method.
  • Create a PhysicalProduct child class.
  • Create a DigitalProduct child 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

Challenge Starter
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.

21

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?

22

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().