LATEST 🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.
🕘 Updated:
Python

Python - Object-Oriented Programming (OOP) Part 2

Inheritance lets classes share common code, polymorphism lets different classes use the same method names, and dunder methods let us customize built-in Python behaviors.

Object-Oriented Programming (OOP) Part 2 – Inheritance, Polymorphism, and Dunder Methods

Quick Answer: Inheritance lets classes share common properties, polymorphism lets different classes use identical method names for custom behavior, and dunder methods let us hook into Python's built-in operators.

Imagine Priya manages financial accounts at a Bengaluru bank for 1,000 customers. Her system handles Savings accounts, Current accounts, and Salary accounts.

Every account requires shared details like name and account number, but each account calculates monthly interest and withdrawal limits differently.

How do we build this robust architecture without repeating boilerplate code across every class?

1. Why Do We Need Inheritance and Polymorphism?

The problem without inheritance

We could write separate classes for every account type, copying and pasting the customer name and balance properties into all of them.

Example 1: Independent bank classes with duplicated code

This code works, but duplicating properties makes future maintenance difficult.

class SavingsAccount:
    def __init__(self, name, balance):
        self.name = name
        self.balance = balance

class CurrentAccount:
    def __init__(self, name, balance):
        self.name = name
        self.balance = balance

Expected output

Classes defined with duplicated fields

This approach runs successfully, but it creates significant design challenges:

  1. Every account class repeats identical initialization logic.
  2. There is no unified way to pass all accounts into a single processing function.
  3. Adding new account types requires rewriting common logic everywhere.

We need a single parent blueprint to hold shared attributes.

The solution: inheritance, polymorphism, and dunder methods

Inheritance = a class receives common members from another class.

Polymorphism = one method call can run different implementations.

Dunder method = a special method surrounded by double underscores that Python invokes automatically.

Comprehensive Bank Account Hierarchy in Priya's System
Base class sharing attributes with multiple specialized child classes
BankAccount (Base) Shared: name, balance
Inherits To
SavingsAccount 4% annual interest
CurrentAccount Overdraft enabled
SalaryAccount Zero balance rule
Base Class Active Step Derived Class

Figure 1: Hierarchical inheritance structure distributing shared attributes and custom behaviors.

2. Implementing Inheritance in Python

Super = a built-in function that refers to the parent class.

Let us write a complete runnable Python program that establishes a base BankAccount and inherits its properties in specialized child classes.

Example 2: Using super() to initialize parent attributes

This code shares constructor logic using inheritance.

class BankAccount:
    def __init__(self, name, balance):
        self.name = name
        self.balance = balance

class SavingsAccount(BankAccount):
    def __init__(self, name, balance, interest_rate):
        super().__init__(name, balance)
        self.interest_rate = interest_rate

if __name__ == "__main__":
    savings = SavingsAccount("Priya", 15000, 0.04)
    print(savings.name, savings.balance, savings.interest_rate)

Expected output

Priya 15000 0.04

Notice how super().__init__() avoids duplicating name and balance assignment.

3. Mastering Polymorphism and Method Overriding

Override = replacing a parent method in a child class with custom logic.

Polymorphism allows us to call calculate_interest() on any account object without caring whether it is a Savings or Current account.

Example 3: Polymorphic interest calculation

Different classes implement the same method name with unique calculations.

class BankAccount:
    def __init__(self, name, balance):
        self.name = name
        self.balance = balance

    def calculate_interest(self):
        return 0

class SavingsAccount(BankAccount):
    def calculate_interest(self):
        return self.balance * 0.04

class CurrentAccount(BankAccount):
    def calculate_interest(self):
        return 0

if __name__ == "__main__":
    accounts = [SavingsAccount("Priya", 10000), CurrentAccount("Arjun", 25000)]
    for acc in accounts:
        print(acc.name, "Interest:", acc.calculate_interest())

Expected output

Priya Interest: 400.0
Arjun Interest: 0

Each object executes its own specific version of calculate_interest() automatically.

4. Deep Dive into Python Dunder Methods

Dunder = double underscore methods that customize core Python operations.

Common dunder methods include __init__ for setup, __str__ for user-friendly printing, and __len__ for object sizing.

Example 4: Implementing string representation and addition dunder methods

Customizing print output and combining account balances with the plus operator.

class BankAccount:
    def __init__(self, name, balance):
        self.name = name
        self.balance = balance

    def __str__(self):
        return $"Holder: {self.name}, Balance: {self.balance}"

    def __add__(self, other):
        return self.balance + other.balance

if __name__ == "__main__":
    acc1 = BankAccount("Priya", 5000)
    acc2 = BankAccount("Arjun", 3000)
    print(acc1)
    print("Combined Balance:", acc1 + acc2)

Expected output

Holder: Priya, Balance: 5000
Combined Balance: 8000

The __add__ dunder method allows us to use the + operator directly on two custom account objects.

Comparing separate classes with an inherited hierarchy
Without Inheritance With Inheritance & Dunder Methods
Repeated constructor code everywhere Centralized setup in base class
Objects print ugly memory addresses Clean readable output via __str__
Manual addition of object attributes Operator overloading using __add__

The important terms to remember

  • Inheritance = sharing common attributes from a parent class.
  • Polymorphism = using identical method names across different classes.
  • Dunder Method = special magic methods like __str__ and __add__.

Design tip: Always implement __str__ and __repr__ in custom classes to make debugging and logging easier.

5. Common Mistakes to Avoid

1. Forgetting to call super().__init__()

Writing a child constructor without invoking parent initialization leaves base attributes uninitialized.

Better approach: Always call super().__init__() at the beginning of child constructors.

6. Interview Questions & Answers

Question 1: What is polymorphism and how does Python support it?

What the interviewer expects: A clear definition showing method overriding in a class hierarchy.

Strong answer: "Polymorphism allows different classes to implement methods with the same name. Python achieves this dynamically through duck typing and method overriding in inherited classes."

What interviewers expect at different levels

  • Junior developer: Understands basic inheritance syntax and method overriding.
  • Senior developer: Knows Method Resolution Order (MRO) and operator overloading.
  • Technical architect: Designs decoupled hierarchies that promote code reuse and scalability.

7. Practice Exercises

Beginner: Hospital staff hierarchy

Create a base Staff class and derived Doctor and Nurse classes with a shared greeting method.

Expected result: Each staff object prints its role-specific greeting.

Intermediate: Custom length dunder

Implement the __len__ dunder method on a custom BankBranch class containing multiple accounts.

Hint: Return the count of accounts using Python's built-in len() function.

8. Frequently Asked Questions (FAQ)

What does MRO mean in Python?

MRO stands for Method Resolution Order, defining the lookup path Python uses to find inherited methods.

Can you override dunder methods?

Yes. Dunder methods are specifically designed to be overridden to customize operator and built-in function behaviors.

9. Next Steps

Now that you have mastered object-oriented inheritance and magic methods, you are ready to explore decorators, closures, and error handling in the next article.

Comments & Ratings (0)

Log in or create a student account to comment and rate this article.

Be the first to comment on this article.