Python Intermediate - Lesson 17 - Inheritance and Composition
Python Intermediate · Lesson 17
Inheritance and Composition
Classes can share behavior through inheritance, or work together by containing instances of other classes. These patterns help organize larger programs, but choosing the simpler relationship matters: a focus block is a kind of study block, while a study plan has study blocks.
super(),
override a method, and use composition to build a larger object from
smaller objects.
1. Inherit from a parent class
A subclass can reuse methods and attributes from a parent class. Put the parent class inside parentheses when defining the subclass.
class StudyBlock:
def __init__(self, topic, minutes):
self.topic = topic
self.minutes = minutes
def summary(self):
return f"{self.topic}: {self.minutes} minutes"
class FocusBlock(StudyBlock):
pass
focus = FocusBlock("Python practice", 30)
print(focus.summary())
FocusBlock inherits StudyBlock's initializer and
summary() method, so the subclass works even though its body
currently contains only pass.
2. Extend parent behavior with super()
Use super() to call a method from the parent class. Here,
FocusBlock adds a goal while keeping the shared topic and
duration behavior.
class FocusBlock(StudyBlock):
def __init__(self, topic, minutes, goal):
super().__init__(topic, minutes)
self.goal = goal
def summary(self):
base_summary = super().summary()
return f"{base_summary} — Goal: {self.goal}"
focus = FocusBlock("Python practice", 30, "write one function")
print(focus.summary())
super().__init__(...) initializes the shared parent
attributes. The subclass's summary() overrides the inherited
version and adds its own information.
3. Use composition for a “has-a” relationship
A study plan is not a type of study block; it contains blocks. Composition keeps the plan responsible for organizing its collection, while each block is responsible for describing itself.
class StudyPlan:
def __init__(self):
self.blocks = []
def add_block(self, block):
self.blocks.append(block)
def total_minutes(self):
return sum(block.minutes for block in self.blocks)
plan = StudyPlan()
plan.add_block(StudyBlock("Loops", 20))
plan.add_block(FocusBlock("Practice problems", 30, "solve two"))
print(plan.total_minutes())
4. Let different objects answer the same method call
If a base block and its subclasses each provide summary(), a
plan can call that method without checking the exact subclass first. This
is a simple example of polymorphism: the same method call can produce
behavior suited to each object's type.
for block in plan.blocks:
print(block.summary())
The loop works with either a regular StudyBlock or a
FocusBlock, as long as each object provides the methods the
plan needs.
Hands-on exercises
-
Create a
TimedBlockclass that inherits fromStudyBlock. Add alabelattribute and overridesummary()to include it. -
Create a
StudyPlanthat contains two different study blocks. Loop through the plan and print each block's summary.
Show Solution & Common Mistakes
Exercise 1 — one possible solution
class StudyBlock:
def __init__(self, topic, minutes):
self.topic = topic
self.minutes = minutes
def summary(self):
return f"{self.topic}: {self.minutes} minutes"
class TimedBlock(StudyBlock):
def __init__(self, topic, minutes, label):
super().__init__(topic, minutes)
self.label = label
def summary(self):
return f"[{self.label}] {super().summary()}"
Exercise 2 — one possible solution
class StudyPlan:
def __init__(self):
self.blocks = []
def add_block(self, block):
self.blocks.append(block)
plan = StudyPlan()
plan.add_block(StudyBlock("Functions", 25))
plan.add_block(TimedBlock("Practice quiz", 15, "Review"))
for block in plan.blocks:
print(block.summary())
Common mistakes:
- Using inheritance just to reuse a few lines when the two concepts are not genuinely “is-a.”
-
Forgetting
super().__init__(...)when a subclass needs attributes initialized by its parent. - Overriding a method but changing its expected behavior so much that code using the parent class no longer works as expected.
- Confusing composition with inheritance: a plan has blocks; it is not itself a block.
- Building many layers of subclasses before a real need for them appears.
Quick quiz
Choose an answer, then select Check answer.
1. Why might a subclass call super().__init__()?
2. Which relationship is composition in this lesson?
3. What does method overriding let a subclass do?
Mini-project: Flexible Study Plan
Create a small study planner using both relationships: focused and review blocks are study blocks, and a plan has a collection of blocks. The plan should summarize every block and calculate total time.
Requirements:
- Create a
StudyBlockparent class with topic, minutes, andsummary(). - Create
FocusBlockandReviewBlocksubclasses. - Use
super()to reuse the parent initializer and summary. - Create a
StudyPlanthat stores block objects and totals their minutes. - Use one loop to print summaries from different block types.
Hints: use isinstance(block, StudyBlock) to
validate what gets added to a plan. Let each block type format its own
summary; the plan only organizes them.
Show Full Project Solution
class StudyBlock:
def __init__(self, topic, minutes):
if not isinstance(topic, str):
raise TypeError("topic must be text")
clean_topic = " ".join(topic.split())
if not clean_topic:
raise ValueError("topic cannot be blank")
if not isinstance(minutes, int) or isinstance(minutes, bool):
raise TypeError("minutes must be an integer")
if minutes <= 0:
raise ValueError("minutes must be greater than zero")
self.topic = clean_topic
self.minutes = minutes
def summary(self):
return f"{self.topic}: {self.minutes} minutes"
class FocusBlock(StudyBlock):
def __init__(self, topic, minutes, goal):
super().__init__(topic, minutes)
if not isinstance(goal, str):
raise TypeError("goal must be text")
clean_goal = " ".join(goal.split())
if not clean_goal:
raise ValueError("goal must be non-blank text")
self.goal = clean_goal
def summary(self):
return f"Focus — {super().summary()} (Goal: {self.goal})"
class ReviewBlock(StudyBlock):
def __init__(self, topic, minutes, source):
super().__init__(topic, minutes)
if not isinstance(source, str):
raise TypeError("source must be text")
clean_source = " ".join(source.split())
if not clean_source:
raise ValueError("source must be non-blank text")
self.source = clean_source
def summary(self):
return f"Review — {super().summary()} (Source: {self.source})"
class StudyPlan:
def __init__(self):
self.blocks = []
def add_block(self, block):
if not isinstance(block, StudyBlock):
raise TypeError("block must be a StudyBlock")
self.blocks.append(block)
def total_minutes(self):
return sum(block.minutes for block in self.blocks)
def summaries(self):
return [block.summary() for block in self.blocks]
def main():
plan = StudyPlan()
plan.add_block(FocusBlock("Python classes", 30, "build a small example"))
plan.add_block(ReviewBlock("SQLite queries", 20, "lesson notes"))
plan.add_block(FocusBlock("Unit testing", 25, "write three tests"))
print("Today's study plan")
for line in plan.summaries():
print(f"- {line}")
print(f"Total: {plan.total_minutes()} minutes")
if __name__ == "__main__":
main()
The subclasses reuse the shared validation and attributes from
StudyBlock, then customize their summaries. The plan stores
all of them in one list and calls summary() on each object.
That shared method call works across the different block types.