Object-Oriented Programming in Python: Inheritance and Polymorphism
Encapsulation, inheritance, overriding and polymorphism, explained with one bank account example you can run.
- Encapsulation with methods and protected attributes
- Inheritance and super()
- Overriding methods and polymorphism
BankAccountbalance, deposit(), month_end()BankAccountmonth_end(): "No interest"SavingsAccountoverrides month_end(): adds interest
What is object-oriented programming in Python?
The problem
As a program grows, many parts need the same kinds of objects with small differences: a normal account and a savings account, a cat and a dog. Copying classes and changing a few lines leads to duplicated code, and checking the type with if everywhere makes every new kind a big change.
Think of it like this
Object-oriented programming works like the accounts of one bank. Every account keeps its balance behind the counter (encapsulation). A savings account is a normal account with one extra feature (inheritance). When the bank says 'month end' to every account, each one does its own version (polymorphism).
self._balance🔒 The money behind the counter: change it only through deposit()class SavingsAccount(BankAccount):🏦 A savings account is an account, plus interestsuper().__init__(owner, balance)📋 Fill in the normal account form firstaccount.month_end()📅 Same request, each account answers its own wayObject-oriented programming organizes a program into classes whose objects keep their own data private (encapsulation), reuse other classes (inheritance) and respond to the same call in their own way (polymorphism).
Object-oriented programming (OOP) models a system as collaborating objects. Each object combines state with the operations allowed on that state, helping larger programs keep responsibilities and change boundaries clear.
The four core OOP principles
- Encapsulation: keep related state and behavior together and expose controlled methods or properties.
- Abstraction: present a useful interface while hiding implementation details callers do not need.
- Inheritance: derive a specialized class from an existing class when there is a genuine is-a relationship.
- Polymorphism: use the same operation with different object types, each providing appropriate behavior.
How this example is designed
- BankAccount owns balance state and validates deposits.
- SavingsAccount reuses the base account contract through inheritance.
- SavingsAccount overrides month_end to apply interest.
- The loop works with every account through the same interface.
When should you use it?
- Several kinds of objects that share most behavior: account types, shapes, game characters.
- Code that must work with new kinds later without being rewritten.
- Protecting data that must stay valid, such as a balance that can never be negative.
When not to use it
- Small scripts with a few functions: classes and inheritance add structure you do not need.
- Deep inheritance chains (A from B from C from D): they are hard to follow; prefer composition.
Basic example
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self._balance = float(balance)
@property
def balance(self):
return self._balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("Deposit must be positive")
self._balance += amount
def month_end(self):
return "No interest"
class SavingsAccount(BankAccount):
def __init__(self, owner, balance, interest_rate):
super().__init__(owner, balance)
self.interest_rate = interest_rate
def month_end(self):
self._balance *= 1 + self.interest_rate
return "Interest applied"
accounts = [
BankAccount("Ada", 100),
SavingsAccount("Lin", 200, 0.05),
]
accounts[0].deposit(50)
for account in accounts:
status = account.month_end()
print(f"{account.owner}: {account.balance:.2f} ({status})")
Result of running the code
Ada: 150.00 (No interest)
Lin: 210.00 (Interest applied)
The four OOP principles in practice
These focused examples show how Python expresses encapsulation, abstraction, inheritance, and polymorphism in everyday code.
Encapsulation
keep related state and behavior together and expose controlled methods or properties.
class BankAccount:
def __init__(self, balance=0):
# Double underscores prevent accidental direct access.
self.__balance = balance
@property
def balance(self):
# Expose read access without exposing mutation.
return self.__balance
def deposit(self, amount):
# Keep validation next to the state it protects.
if amount <= 0:
raise ValueError("Amount must be positive")
self.__balance += amount
account = BankAccount(100)
account.deposit(50)
print(account.balance) # 150
Abstraction
present a useful interface while hiding implementation details callers do not need.
from abc import ABC, abstractmethod
class PaymentMethod(ABC):
@abstractmethod
def pay(self, amount):
# Callers know what pay does, not how each provider does it.
pass
class CreditCard(PaymentMethod):
def pay(self, amount):
# The concrete class hides its payment implementation.
return f"Paid ${amount:.2f} by card"
payment = CreditCard()
print(payment.pay(25))
Inheritance
derive a specialized class from an existing class when there is a genuine is-a relationship.
class Employee:
def __init__(self, name):
self.name = name
def describe(self):
return self.name
class Developer(Employee):
def __init__(self, name, language):
# Reuse initialization from the parent class.
super().__init__(name)
self.language = language
def describe(self):
# Extend inherited behavior instead of duplicating it.
return f"{super().describe()} writes {self.language}"
print(Developer("Ada", "Python").describe())
Polymorphism
use the same operation with different object types, each providing appropriate behavior.
class EmailNotification:
def send(self, message):
return f"Email: {message}"
class SmsNotification:
def send(self, message):
return f"SMS: {message}"
def notify(channels, message):
for channel in channels:
# The same call selects behavior from each concrete object.
print(channel.send(message))
channels = [EmailNotification(), SmsNotification()]
notify(channels, "Order shipped")
Code explanation
BankAccount encapsulates its balance and exposes controlled operations. SavingsAccount inherits that interface and overrides month_end. The loop treats both objects uniformly, so the method selected at runtime depends on the concrete object.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change the input and predict the output before running.
- Handle empty or invalid input.
- Wrap the logic in a function and add more test cases.
Common mistakes
Forgetting to call super().__init__
Without it the parent's setup never runs and attributes such as owner are missing.
class SavingsAccount(BankAccount):
def __init__(self, owner, balance, rate):
self.interest_rate = rate
class SavingsAccount(BankAccount):
def __init__(self, owner, balance, rate):
super().__init__(owner, balance)
self.interest_rate = rate
Changing protected data directly
Setting _balance from outside skips the checks in deposit().
account._balance = -500
account.deposit(50)
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
All challenges