Inheritance
Overview
Often several classes are variations on a theme: a savings account and a checking account are both accounts; a cat and a dog are both animals. Inheritance lets you write the shared parts once, in a parent (base) class, and create child classes (subclasses) that reuse them and add or change only what’s different.
Creating a subclass
Put the parent class in brackets after the new class’s name:
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
raise ValueError("insufficient funds")
self.balance -= amount
class SavingsAccount(Account):
def add_interest(self, rate):
self.deposit(self.balance * rate)SavingsAccount has no __init__, deposit or withdraw of its own — it inherits them:
s = SavingsAccount("Asha", 1000)
s.deposit(500) # Account's method
s.add_interest(0.05) # SavingsAccount's own method
print(s.balance) # 1575.0When you call a method, Python looks in the object’s own class first, then in its parent, then the parent’s parent, and so on. Every class ultimately inherits from object, which provides defaults like the basic __repr__.
Overriding methods
Define a method with the same name in the subclass, and it replaces the parent’s version for that subclass:
class CheckingAccount(Account):
def withdraw(self, amount):
if amount > self.balance + 200: # allow a 200 overdraft
raise ValueError("overdraft limit reached")
self.balance -= amountAccount objects still use the original withdraw; CheckingAccount objects use the new one. Code that calls account.withdraw(50) doesn’t need to know which kind of account it has — each object does the right thing. That’s called polymorphism.
super(): extending the parent
Often you want to add to the parent’s behaviour rather than replace it. super() gives you access to the parent’s version:
class SavingsAccount(Account):
def __init__(self, owner, balance=0, rate=0.02):
super().__init__(owner, balance) # let Account set owner and balance
self.rate = rate # then add our own attribute
def add_interest(self):
self.deposit(self.balance * self.rate)Forgetting super().__init__(...) is a common bug: the parent’s setup never runs, and you get AttributeError: 'SavingsAccount' object has no attribute 'balance' later.
super() works in any method, not just __init__:
class LoggedAccount(Account):
def withdraw(self, amount):
print(f"Withdrawing {amount}")
super().withdraw(amount) # then do the normal thingisinstance and issubclass
An instance of a subclass counts as an instance of the parent too:
s = SavingsAccount("Asha")
isinstance(s, SavingsAccount) # True
isinstance(s, Account) # True — a savings account IS an account
isinstance(s, CheckingAccount) # False
issubclass(SavingsAccount, Account) # True
type(s).__name__ # 'SavingsAccount'That’s how except ValueError also catches subclasses of ValueError, and how your custom exceptions from Raising exceptions work: class InsufficientFundsError(Exception) is inheritance.
Writing type(self).__name__ in a parent’s __repr__ is a handy trick: each subclass then shows its own name automatically.
“Is a” vs “has a”: composition
Inheritance models an “is a” relationship: a savings account is an account. It’s easy to overuse. Ask: is the child really a specialised kind of the parent, usable anywhere the parent is?
Many relationships are “has a”: a car has an engine; a library has books; a customer has accounts. For those, store one object inside another — composition:
class Customer:
def __init__(self, name):
self.name = name
self.accounts = [] # a Customer HAS accounts
def total_balance(self):
return sum(a.balance for a in self.accounts)class Customer(Account) would be wrong: a customer isn’t a kind of account.
Guidelines:
- Prefer composition by default; it’s more flexible.
- Use inheritance when subclasses genuinely share an interface and behaviour, and keep hierarchies shallow (one or two levels).
- Python allows multiple inheritance (
class C(A, B):) — it’s used for small “mixin” classes in frameworks, but avoid it in your own designs until you need it.
Abstract base classes
Sometimes a parent class exists only to be inherited — “every shape must have an area()”. The abc module can enforce that:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self): ...
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
Shape() # TypeError: Can't instantiate abstract class Shape without an implementation for abstract method 'area'
Square(3).area() # 9Remember: subclasses inherit everything, override what differs, and call
super()to build on the parent. Use inheritance for “is a” — and composition for “has a”.
Bank accounts
Write a base class Account(owner, balance=0) with deposit(amount), withdraw(amount) (raise ValueError("insufficient funds") if it would go below zero) and a __repr__. Then: SavingsAccount(Account) adds a rate (passed to __init__ and set after calling super().__init__) and an add_interest() method; CheckingAccount(Account) adds an overdraft limit and overrides withdraw so the balance may go down to minus the overdraft. Create one of each, run the operations in the starter, and print the accounts and the isinstance checks.
class Account:
...
class SavingsAccount(Account):
...
class CheckingAccount(Account):
...
savings = SavingsAccount("Asha", 1000, rate=0.05)
checking = CheckingAccount("Ben", 100, overdraft=200)
savings.add_interest()
checking.withdraw(250) # allowed: balance -150
# checking.withdraw(100) should fail: it would go below -200class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
raise ValueError("insufficient funds")
self.balance -= amount
def __repr__(self):
return f"{type(self).__name__}({self.owner!r}, {self.balance})"
class SavingsAccount(Account):
def __init__(self, owner, balance=0, rate=0.02):
super().__init__(owner, balance)
self.rate = rate
def add_interest(self):
self.deposit(self.balance * self.rate)
class CheckingAccount(Account):
def __init__(self, owner, balance=0, overdraft=0):
super().__init__(owner, balance)
self.overdraft = overdraft
def withdraw(self, amount):
if amount > self.balance + self.overdraft:
raise ValueError("overdraft limit reached")
self.balance -= amount
savings = SavingsAccount("Asha", 1000, rate=0.05)
checking = CheckingAccount("Ben", 100, overdraft=200)
savings.add_interest()
checking.withdraw(250) # allowed: balance -150
try:
checking.withdraw(100)
except ValueError as error:
print("Error:", error)
print(savings, checking) # SavingsAccount('Asha', 1050.0) CheckingAccount('Ben', -150)
print(isinstance(savings, Account), isinstance(checking, SavingsAccount)) # True FalseSummary
class Child(Parent):creates a subclass that inherits all the parent’s attributes and methods.- Define a method with the same name to override it; call the parent’s version with
super().method(...). - A subclass’s
__init__should callsuper().__init__(...)so the parent’s setup still happens. isinstance(obj, Parent)is True for instances of subclasses too — an object of a subclass *is a* parent.- Use inheritance for genuine “is a” relationships; for “has a”, store one object inside another (composition).