Classes and objects
Composition and inheritance
Choose how objects relate to each other.
Lesson 52 of 63
Reading: about 1 min
Lesson + practice: about 16 min
Difficulty: Intermediate
On this page5 sections
Composition stores an object inside another object. Inheritance lets a subclass specialize a base class. Prefer the simpler relationship that accurately describes your model.
Worked example
class Session:
def __init__(self, minutes):
self.minutes = minutes
class Plan:
def __init__(self, sessions):
self.sessions = sessions
def total(self):
return sum(item.minutes for item in self.sessions)
print(Plan([Session(20), Session(25)]).total())45
Why this works
A plan has sessions, so composition represents that relationship directly. The total method adds their durations.
Another case
class Report:
def label(self):
return "report"
class DailyReport(Report):
def label(self):
return "daily report"
print(DailyReport().label())daily report
Python finds DailyReport.label first. If DailyReport did not define label(), the inherited Report.label would run instead.
Practice
Would Plan inheriting from Session represent the same relationship?
Check the practice result
Reveal answer
No. A plan contains sessions; it is not a kind of session.
Try another case
A Report holds a list of Session objects. Is that composition or inheritance?
Check your answer
Reveal answer
Composition. A report contains sessions; it is not a kind of session, so it stores them as an attribute.
Your progress
Reveal the check answer or reach the end to complete this lesson.