Object-Oriented Programming (OOP) in Python: Inheritance, Dunder Methods & Polymorphism

Master real-world OOP patterns in Python: classes, private attributes, super() inheritance, and operator overloading with magic methods.

Object-Oriented Programming (OOP) in Python: Inheritance, Dunder Methods & Polymorphism

Python is an object-oriented language down to its very core. Everything in PythonÔÇöincluding integers, functions, and modulesÔÇöis a first-class object that descends from the base object class.

1. Encapsulation with Properties and Dunder Variables

Python does not enforce access specifiers like C++ or Java with keywords such as private or protected. Instead, naming conventions indicate intent, and @property decorators provide controlled access:

bank_account.py
class BankAccount:
    """Represents a secure bank balance with validation."""
    
    def __init__(self, owner: str, initial_deposit: float = 0.0) -> None:
        self.owner = owner
        self._balance = max(0.0, float(initial_deposit))  # Protected convention
        
    @property
    def balance(self) -> float:
        """Getter for the account balance."""
        return self._balance
        
    def deposit(self, amount: float) -> None:
        if amount <= 0:
            raise ValueError("Deposit amount must be strictly positive.")
        self._balance += amount
        print(f"Deposited ${amount:,.2f}. New Balance: ${self._balance:,.2f}")
        
    def withdraw(self, amount: float) -> bool:
        if amount > self._balance:
            print("Insufficient funds! Transaction declined.")
            return False
        self._balance -= amount
        print(f"Withdrew ${amount:,.2f}. Remaining: ${self._balance:,.2f}")
        return True

    def __str__(self) -> str:
        """User-friendly string representation."""
        return f"BankAccount(Owner={self.owner}, Balance=${self._balance:,.2f})"

# Demonstration
account = BankAccount("Sarah Connor", 1500)
account.deposit(450.50)
account.withdraw(200)
print(account)

2. Inheritance and the super() Method Resolution Order (MRO)

When sub-classing in Python, the C3 linearization algorithm resolves method lookups via the Method Resolution Order (MRO):

inheritance_hierarchy.py
class SavingsAccount(BankAccount):
    def __init__(self, owner: str, initial_deposit: float, interest_rate: float = 0.035) -> None:
        super().__init__(owner, initial_deposit)
        self.interest_rate = interest_rate
        
    def apply_interest(self) -> float:
        accrued = self._balance * self.interest_rate
        self.deposit(accrued)
        return accrued

savings = SavingsAccount("Sarah Connor", 5000, 0.05)
savings.apply_interest()
print(SavingsAccount.__mro__)

3. Magic (Dunder) Methods Overview

Magic methods allow custom classes to integrate smoothly with native Python syntax:

Dunder Method Python Operator / Trigger Purpose
__init__(self) obj = ClassName() Object constructor / attribute setup
__str__(self) str(obj) or print(obj) Human-readable display representation
__repr__(self) Interactive REPL inspect Unambiguous developer-oriented string
__add__(self, other) obj1 + obj2 Custom operator overloading for addition
__len__(self) len(obj) Returns the collection length
__enter__ / __exit__ with obj as x: Context manager protocol for cleanup
Related Tags: #Python #OOP

Discussion (0)

Leave a Thought or Question

No comments posted yet. Be the first to start the discussion!