Reuse without the knot.
Extend behaviour carefully and recognise when composition is simpler.
01 The idea
Inheritance lets a child class reuse and specialise a parent class. A method with the same name overrides the inherited behaviour. super() lets a subclass cooperate with the next implementation in the method resolution order. Use inheritance when the child really is a specialised form of the parent.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
class Task:
def label(self):
return "Task"
class UrgentTask(Task):
def label(self):
return f"{super().label()}: urgent"
print(UrgentTask().label())Task: urgent
03 Under the hood
- 1
UrgentTask names Task as its parent. It inherits behaviour and can replace or extend individual methods.
- 2
The overridden label() calls the parent implementation through super(), then adds detail.
- 3
When one object merely uses another, prefer composition: store that object as an attribute instead of forcing an inheritance relationship. Keep hierarchies shallow and responsibilities clear.
04 Your turn, builder
Define a Tool with a describe() method returning "Tool". Override it in a PythonTool subclass to return "Python tool".
Reveal one possible solution +
class Tool:
def describe(self):
return "Tool"
class PythonTool(Tool):
def describe(self):
return "Python tool"
print(PythonTool().describe())05 Check your signal
What is overriding?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.