Python OOP Made Simple: Meet Your Code Avengers (Part -2 ) Core Component
Last Updated on July 30, 2026 by Editorial Team
Author(s): Debasish Das
Originally published on Towards AI.
Python OOP Made Simple: Meet Your Code Avengers (Part -2 ) Core Component

In Part 1, we laid down the foundational concrete. We learned how to build our superhero blueprints (Classes), bring them to life (Objects), run the initial configuration scripts (Constructors), and wrap our secret sauce in a protective layer (Encapsulation).
But a superhero who can only stand still and protect their own pockets isn’t saving the universe anytime soon. To assemble a truly unstoppable codebase, we need to unlock the absolute superpowers of Object-Oriented Programming.
Welcome to Phase 2: The Core Pillars.
We’ve already mastered Encapsulation in our last training session, so grab your capes as we dive into the remaining three superpowers that turn messy scripts into architectural masterpieces:
- Inheritance 🧬 (The Family Tree): How to pass Iron Man’s armor technology down to War Machine without rewriting a single line of code.
- Polymorphism 🎭 (The Chameleon Effect): How the exact same command can make Iron Man fire a repulsor blast while Spider-Man shoots a web constraint.
- Abstraction 🎛️ (The Control Panel): How to smash the gas pedal of the Batmobile without needing a degree in internal combustion engineering.
Inheritance (The Family Tree):
- Concept: Inheritance is a core Object-Oriented Programming (OOP) concept that allows a new class to acquire the properties (attributes) and behaviours (methods) of an existing class. It establishes an “is-a” relationship, enabling you to reuse code, minimize redundancy, and build organized, hierarchical software architectures.
# Parent Class
class User:
def __init__(self):
self.name = 'Debasish'
self.gender = 'male'
def login(self): # Method of the User class
print('login')
# Child Class
class Student(User): # Invokeing Parent class
def enroll(self): # Method of the Student class
print('enroll into the course')
s = Student() # Instance of the Student Class
print(s.name) # Student instance `s` uses User class attributes `name`
s.login() ## Student instance `s` uses User class method `login`
s.enroll()
# Output
Debasish
login
enroll into the course
- What gets inherited?
- A class can inherit from another class.
- The child class inherits the constructor, attributes, and methods.
- The parent has no access to the child’s class.
- Private properties of the parent are not accessible directly in the child class.
- A child class can override the attributes or methods. This is called method overriding.
- super() is an inbuilt function that is used to invoke the parent class methods and constructor.
- Key Function
super():superis a keyword or function used to refer directly to the immediate parent class (superclass). It acts as a bridge that allows a child class (subclass) to access constructors, methods, and variables from its parent without hardcoding the parent's name.
# Parent Class
class Parent:
def __init__(self,num):
print("This is in parent class")
self.__num=num
def get_num(self):
return self.__num
# Child Class
class Child(Parent):
def __init__(self,val,num):
print("This is in child class")
self.__val=val
def get_val(self):
return self.__val
son=Child(100,10)
print("Child: Val:",son.get_val())
print("Parent: Num:",son.get_num())
# Output
This is in child class
Child: Val: 100
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
/tmp/ipykernel_590/2216681809.py in <cell line: 0>()
19 son=Child(100,10)
20 print("Child: Val:",son.get_val())
---> 21 print("Parent: Num:",son.get_num())
/tmp/ipykernel_590/2216681809.py in get_num(self)
6
7 def get_num(self):
----> 8 return self.__num
9
10 class Child(Parent):
AttributeError: 'Child' object has no attribute '_Parent__num'
In the previous example, an AttributeError occurs because Python does not automatically call the parent class's constructor (__init__) if the child class defines its own.
When you instantiate the Child object, Python finds the __init__ constructor inside the Child class and executes it, completely skipping the Parent constructor. As a result, the __num variable is never initialized.
To solve this problem, we use the built-in super() function. This function acts as a bridge, allowing the child class to explicitly invoke the parent class's constructor and methods.
Here is the corrected code:
# Parent Class
class Parent:
def __init__(self, num):
print("This is in parent class")
self.__num = num
def get_num(self):
return self.__num
# Child Class
class Child(Parent):
def __init__(self, val, num):
# Invoke the Parent class constructor using super()
super().__init__(num)
# In same way, Parent class methods using Child class using `super().get_num()`
print("This is in child class")
self.__val = val
def get_val(self):
return self.__val
# Creating an instance of the Child Class
son = Child(100, 10)
print("Child Val:", son.get_val())
print("Parent Num:", son.get_num())
# Output
This is in parent class
This is in child class
Child Val: 100
Parent Num: 10
Constructor Overriding: If a child class has an __init__ method, it overrides the parent's __init__.
The Role of super(): super().__init__(arguments) passes the required data up to the parent class so it can initialize its private/protected variables properly before the child class proceeds with its own initialization.
- Types of Inheritance: Think of it as building a family tree of transport:
- Single Inheritance: A basic relationship (Parent → Child).
- Multilevel Inheritance: A chain of generations (Grandparent →Parent → Child).
- Hierarchical Inheritance: One parent having multiple distinct children.
- Multiple Inheritance: A child class that inherits traits from two entirely separate parent classes (like a flying car).

- Analogy: Iron Man passing his armor technology down to War Machine or Ironheart.
Polymorphism (The Chameleon Effect):
- Concept: The ability of different classes to respond to the same method call in their own unique way.
- Analogy: Think of how you act in real life. Your behavior changes depending on who you are interacting with. How you behave in front of your parents is completely different from how you act around your friends or your boss. You are the exact same person, but you take on different forms based on the interaction or context. In OOP, this chameleon-like trait is exactly what we call polymorphism.
- Types of Polymorphism:
- Method Overriding (runtime polymorphism): Method overriding occurs when a child class provides a specific implementation for a method that is already defined in its parent class. It allows a child class to change or refine the behavior of inherited actions to better fit its specific purpose.
# Parent Class (The Base Blueprint)
class Avenger:
def __init__(self, name):
self.name = name
def use_superpower(self):
# Default behavior for any generic hero
print(f"{self.name} throws a standard punch!")
# Child Class 1 (Overrides the default behavior)
class IronMan(Avenger):
def use_superpower(self):
print(f"{self.name} fires a high-tech Repulsor Blast! 💥")
# Child Class 2 (Overrides the default behavior differently)
class SpiderMan(Avenger):
def use_superpower(self):
print(f"{self.name} shoots a Web-Shooter restraint! 🕸️")
# --- How it works ---
tony = IronMan("Tony Stark")
peter = SpiderMan("Peter Parker")
tony.use_superpower() # Output: Tony Stark fires a high-tech Repulsor Blast! 💥
peter.use_superpower() # Output: Peter Parker shoots a Web-Shooter restraint! 🕸️
2. Method Overloading: A class has multiple methods with the exact same name, but they accept different inputs (different numbers of arguments or different data types).
Think of it like a “Login” system:
login(username, password)login(phone_number, otp)
It’s the same action (login), but how you trigger it depends on what information you pass into it.
Python doesn't support traditional overloading!
3. Operator overloading: Operator Overloading is a feature in object-oriented programming that allows you to change how a built-in mathematical or logical operator (like +, -, *, or ==) behaves when it is used with your custom objects.
class Hero:
def __init__(self, name, power_level):
self.name = name
self.power_level = power_level
# Overloading the '+' operator
def __add__(self, other):
# We define exactly what happens when two Hero objects meet a '+' sign
combined_power = self.power_level + other.power_level
return f"Team-up Power Level: {combined_power} 🔥"
# --- Creating our objects ---
thor = Hero("Thor", 95)
hulk = Hero("Hulk", 98)
# --- Using the overloaded operator ---
# Instead of writing a clunky function like thor.combine_power(hulk)...
# We can just use the clean, natural '+' sign!
result = thor + hulk
print(result) # Output: Team-up Power Level: 193 🔥
Abstraction (The Control Panel):
- Concept: Hiding complex implementation details and showing only the essential features.
- Analogy: Driving a car — you press the gas pedal (interface), but you don’t need to know how the internal combustion engine manages fuel injection (hidden complexity).
- 🛠️ How Abstraction Works in Python
To bring abstraction into your Python code, you need three key ingredients:
- The
abcModule: Python doesn't have abstract classes built-in by default. We have to import theabcmodule (which stands for Abstract Base Classes). - The
@abstractmethodDecorator: This is a special marker we place over a method inside our parent class. It acts as a strict rule saying: "Any child class that inherits from me MUST write its own custom version of this method." - Why you cannot instantiate an abstract class directly: An abstract class is just an incomplete, hollow blueprint. Because it only declares actions without actually defining how they work, Python will completely block you from creating an object directly from it (e.g.,
weapon = WeaponSystem()will crash your program). It exists purely to be inherited by concrete child classes.
# Step 1: Import the necessary tools from the 'abc' module
from abc import ABC, abstractmethod
# Step 2: Create the Abstract Base Class (Inherits from ABC)
class WeaponSystem(ABC):
@abstractmethod
def activate(self):
"""This is an abstract method. No actual code goes here!"""
pass
# Step 3: Implement the concrete child classes
class RepulsorLaser(WeaponSystem):
def activate(self):
# Specific complex engineering for Iron Man
print("Charging arc reactor... Diverting power... Firing Laser! ⚡")
class WebShooter(WeaponSystem):
def activate(self):
# Specific mechanical details for Spider-Man
print("Compressing web-fluid... Releasing pressure valve... Thwip! 🕸️")
# --- How it works ---
# 🛑 CRITICAL RULE: This will throw a TypeError!
# You CANNOT instantiate an abstract class directly because it's just a hollow template.
# basic_weapon = WeaponSystem()
# Instead, we create real, concrete objects from the child classes:
tony_weapon = RepulsorLaser()
peter_weapon = WebShooter()
tony_weapon.activate() # Output: Charging arc reactor... Firing Laser! ⚡
peter_weapon.activate() # Output: Compressing web-fluid... Thwip! 🕸️
What’s next? Drop a comment below with your favorite OOP pillar, and don’t forget to smash that clap button if this guide helped clear your anxiety! And try out the notebook for better understanding🦸♂️✨.
If you have any questions, feel free to ask me. Buy some coffee🍵 for me.
Thank you for visiting! I plan to add more questions in the future. If you enjoyed this, please follow me on Medium for more updates.
Check Out My Other Blogs
- CNNs Explained: How Convolutional Neural Networks Actually Work
- PyTorch Mastery: Complete Deep Learning Guide (2025 Edition)
- Master LangChain in 2025: From RAG to Tools (Complete Guide)
Join thousands of data leaders on the AI newsletter. Join over 80,000 subscribers and keep up to date with the latest developments in AI. From research to projects and ideas. If you are building an AI startup, an AI-related product, or a service, we invite you to consider becoming a sponsor.
Published via Towards AI
Towards AI Academy
We Build Enterprise-Grade AI. We'll Teach You to Master It Too.
15 engineers. 100,000+ students. Towards AI Academy teaches what actually survives production.
Start free — no commitment:
→ 6-Day Agentic AI Engineering Email Guide — one practical lesson per day
→ Agents Architecture Cheatsheet — 3 years of architecture decisions in 6 pages
Our courses:
→ AI Engineering Certification — 90+ lessons from project selection to deployed product. The most comprehensive practical LLM course out there.
→ Agent Engineering Course — Hands on with production agent architectures, memory, routing, and eval frameworks — built from real enterprise engagements.
→ AI for Work — Understand, evaluate, and apply AI for complex work tasks.
Note: Article content contains the views of the contributing authors and not Towards AI.