Objects and lazy iteration · Lesson 22 of 25
Inheritance and composition
Reuse behavior with an appropriate relationship.
8 minutes2 games
Inheritance models “is a”: class Student(Person). A subclass may add or override methods; super() follows the method resolution order. Composition stores another object as a field and often better represents “has a”.
Python
class Person:
def __init__(self, name):
self.name = name
def greet(self):
return f"Hi {self.name}"
class Student(Person):
def __init__(self, name, level):
super().__init__(name)
self.level = level
student = Student("Mona", 2)
print(student.greet())
print(student.level)- Person
- Student
- Teacher
Quick question
A car has an engine. Which relationship is clearer?
Exercise
Make Dog inherit Animal and override sound to return woof. Print Dog().sound().
Expected output: woof
Python
class Animal:
def sound(self):
return "?"
Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.