👋 Work With Me

I help startups and teams build production-ready apps with Django, Flask, and FastAPI.

Let’s Talk →

I'm always excited to take on new projects and collaborate with innovative minds.

Address

No 7 Street E, Federal Low-cost Housing Estate, Kuje, Abuja 903101, Federal Capital Territory

Social Links

Tutorials

Python Tutorial – Lesson 16: Inheritance, Encapsulation & Polymorphism in Depth

Inheritance allows a child class to reuse code from a parent class. This reduces duplication and makes code more organized.

Python Tutorial – Lesson 16: Inheritance, Encapsulation & Polymorphism in Depth

In Lesson 15, we introduced Object-Oriented Programming (OOP) concepts in Python.
Now, let’s go deeper into three powerful OOP pillars:

  • Inheritance (code reusability)
  • Encapsulation (data protection)
  • Polymorphism (flexibility with methods)

🔹 1. Inheritance in Depth

Inheritance allows a child class to reuse code from a parent class.
This reduces duplication and makes code more organized.

Basic Example:

 
# Parent class
class Animal:
   def __init__(self, name):
       self.name = name
       
   def speak(self):
       print(f"{self.name} makes a sound.")
       
# Child class inheriting Animal
class Dog(Animal):
   def speak(self):
       print(f"{self.name} barks!")
       
class Cat(Animal):
   def speak(self):
       print(f"{self.name} meows!")
       
dog = Dog("Buddy")
cat = Cat("Whiskers")
dog.speak()   # Buddy barks!
cat.speak()   # Whiskers meows!

 


Types of Inheritance in Python

  1. Single Inheritance → One parent, one child.
  2. Multiple Inheritance → A child inherits from multiple parents.
  3. Multilevel Inheritance → A class inherits from another child class.
  4. Hierarchical Inheritance → Multiple children inherit from the same parent.

Example of Multiple Inheritance:

 
class Flyer:
   def fly(self):
       print("I can fly!")
       
class Swimmer:
   def swim(self):
       print("I can swim!")
       
class Duck(Flyer, Swimmer):
   pass
   
duck = Duck()
duck.fly()
duck.swim()

Output:

 
I can fly!
I can swim!

🔹 2. Encapsulation in Depth

Encapsulation is about restricting direct access to data.
Python doesn’t enforce it strictly, but uses naming conventions:

  • _attribute → Protected (by convention, avoid direct access)
  • __attribute → Private (name mangling applied)
 
class BankAccount:
   def __init__(self, balance):
       self.__balance = balance   # Private attribute
       
   def deposit(self, amount):
       self.__balance += amount
       
   def withdraw(self, amount):
       if amount <= self.__balance:
           self.__balance -= amount
       else:
           print("Insufficient funds!")
           
   def get_balance(self):
       return self.__balance
       
account = BankAccount(100)
account.deposit(50)
account.withdraw(30)
print(account.get_balance())   # 120

🔹 3. Polymorphism in Depth

Polymorphism means many forms — same method name, different behavior.

Example 1: Same Method in Different Classes

 
class Bird:
   def speak(self):
       print("Chirp!")
       
class Dog:
   def speak(self):
       print("Woof!")
       
for animal in (Bird(), Dog()):
   animal.speak()

Output:

 
Chirp!
Woof!

Example 2: Method Overriding

Child class provides a new version of a method that exists in the parent.

 
class Vehicle:
   def move(self):
       print("The vehicle moves.")
       
class Car(Vehicle):
   def move(self):
       print("The car drives.")
       
class Boat(Vehicle):
   def move(self):
       print("The boat sails.")
       
for v in (Car(), Boat()):
   v.move()

Output:

 
The car drives.
The boat sails.

Example 3: Duck Typing (Python-Style Polymorphism 🦆)

Python cares about behavior, not type.
If an object has the method, it works — even if it’s a totally different class.

 
class Laptop:
   def execute(self):
       print("Running code...")
       
class Human:
   def execute(self):
       print("Solving problems...")
       
def code(obj):
   obj.execute()
   
code(Laptop())  # Running code...
code(Human())   # Solving problems...

📝 Quick Recap

  • Inheritance → Reuse parent class code (supports single, multiple, multilevel, hierarchical).
  • Encapsulation → Protect data using private/protected attributes.
  • Polymorphism → Same method name, different behaviors (via overriding, duck typing).

These three principles make your Python code more modular, secure, and flexible.


🎯 Practice Exercises

  1. Create a base class Shape with a method area().
    • Inherit Rectangle and Circle classes.
    • Implement correct area() for each shape.
  2. Create a BankAccount class with deposit, withdraw, and check_balance.
    • Prevent direct access to the balance using encapsulation.
  3. Write a Vehicle parent class.
    • Create Car, Bike, and Plane child classes.
    • Override the move() method for each.
    • Demonstrate polymorphism by looping over all vehicles.

 

Up Next Lesson 17: Mini Project   

💼 Need a Developer?

I'm Kingsley Odume, a Django, Flask, and FastAPI developer with experience building SaaS platforms, APIs, and modern web apps. If you're a recruiter or business owner looking for a reliable software developer, let's connect!

🚀 Hire Me

Python, Python tutorials, Python Beginners series, Python Step-byStep
4 min read
Aug 20, 2025
By Kingsley Odume
Share

Leave a comment

Your email address will not be published. Required fields are marked *

Related posts

Aug 29, 2025 • 3 min read
Step-by-Step: Building a SaaS App with Django + Stripe Payments

Learn how to build a real-world SaaS app with Django and Stripe paymen...

Aug 21, 2025 • 3 min read
Final Wrap-Up: Python Tutorial Series for Beginners

Congratulations on completing the Python Tutorial Series! 🚀 In this w...

Aug 20, 2025 • 4 min read
Final Lesson: Mini Project – Putting It All Together in Python

In this final lesson, we’ll bring all those concepts together in a Min...

Your experience on this site will be improved by allowing cookies. Cookie Policy