Lesson 24 of 30
In progress
Inheritance and super()
Extend a class without copying it, override methods safely, and recognise when composition is the better answer.
Copying a class to change one method means two places to fix the same bug. Inheritance lets a new class reuse behaviour and change only what differs, provided the relationship is genuinely "is a kind of".
What you will learn
- Create a subclass that extends a base class.
- Call the parent constructor with
super()and override methods safely. - Decide between inheritance and composition.
A subclass is a specialisation
class Savings(Account) means every Savings object is also an Account: it has the same attributes and methods, plus anything added.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
def describe(self):
return f"{self.owner} has {self.balance}"
class Savings(Account):
def __init__(self, owner, balance=0, rate=0.04):
super().__init__(owner, balance)
self.rate = rate
def add_interest(self):
self.balance += self.balance * self.rate
return self.balance
basic = Account("Ravi", 100)
savings = Savings("Ana", 1000, 0.05)
print(basic.describe())
print(savings.describe())
print(savings.add_interest())
Press Run to see the output.
Savings inherits describe without writing it. super().__init__(owner, balance) runs the parent’s constructor so the shared attributes are set in one place. Then Savings adds its own rate.
savings.describe() works even though describe was defined on Account, because attribute lookup climbs from the instance to its class and then to the base class.
Overriding replaces, extending keeps both
A subclass can redefine a method to change behaviour. The override wins for instances of the subclass.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
def describe(self):
return f"{self.owner} has {self.balance}"
class Savings(Account):
def describe(self):
return f"Savings: {super().describe()}"
print(Account("Ravi", 100).describe())
print(Savings("Ana", 1000).describe())
Press Run to see the output.
super().describe() calls the parent version and wraps its text, so the shared formatting is not duplicated. If the parent’s wording changes, both classes follow.
isinstance and the "is a" test
isinstance checks whether an object is an instance of a class or any of its bases.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
class Savings(Account):
pass
acc = Savings("Ana", 100)
print(isinstance(acc, Savings))
print(isinstance(acc, Account))
print(isinstance(acc, str))
Press Run to see the output.
That is the useful test for a subclass: it passes for both. It is also why inheritance is a promise. Code that accepts an Account will receive Savings and must keep working, so a subclass must not require extra setup its parent’s callers do not provide.
Composition is often the better answer
Inheritance says "is a kind of". Composition says "has a". If you catch yourself creating class SavingsAccountWithFeesAndStatements(Account), you probably want small objects that work together instead.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
def render(self):
return f"Statement for {self.account.owner}: {self.account.balance}"
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
acc = Account("Ana", 500)
print(Statement(acc).render())
Press Run to see the output.
Statement has an account rather than being one. It can be tested alone, reused with any object that has owner and balance, and changed without touching the account class. Prefer this when the new class is not truly a subtype.
With a single base class the lookup is a straight line: instance, subclass, base. With several bases Python follows the method resolution order, a consistent sequence you can inspect with Savings.__mro__. You rarely need to read it, but it explains why the first base in the list wins when two parents define the same method.
The safest inheritance is shallow and honest: one base class, a clear specialisation, and a base that never needs to know which subclasses exist. If the base ever checks isinstance(self, Savings), the hierarchy has started to leak and composition would be simpler. Composition also avoids the fragile base class problem entirely, because collaborating objects only promise the methods they actually use.
Deep hierarchies are hard to follow and fragile when a base class changes. Two levels is usually plenty for application code; reach for composition beyond that.
Forgetting super().__init__() in a subclass leaves the parent’s attributes unset, and the failure appears later as AttributeError: 'Savings' object has no attribute 'owner'. If the subclass defines __init__, call the parent constructor first, before adding its own attributes.
Create a base Shape with a describe() method that returns the shape’s name and area. Add Circle and Rectangle subclasses that each implement area(). Put both in a list and print each description.
Show solution
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
def area(self):
raise NotImplementedError
def describe(self):
return f"{self.name}: area {self.area():.2f}"
class Circle(Shape):
name = "circle"
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14159 * self.radius ** 2
class Rectangle(Shape):
name = "rectangle"
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
for shape in [Circle(2), Rectangle(3, 4)]:
print(shape.describe())
Press Run to see the output.
describe is written once and calls area(), which each subclass supplies. NotImplementedError in the base class documents the contract without forcing an abstract base class on a beginner program.
Recap
- A subclass inherits attributes and methods and can add or override.
super().__init__()sets up the parent part before the subclass adds its own.- Inheritance is for "is a kind of"; composition is for "has a" and is usually more flexible.
Next, you will put classes, validation and exceptions together in a small bank account project.
Can a class inherit from two classes?
What happens if a subclass does not define __init__?
Progress is saved in this browser only. No account, no email.