CSCI 127 Joy and Beauty of Data · Unit 3: Object-oriented programming · on Exam 2
3.2 More object orientation: inheritance
Study notes for More object orientation: inheritance in CSCI 127 Joy and Beauty of Data at Montana State University: the big ideas, code you should know, a worked example, common mistakes and an exam tip. The same topic has endless practice questions and flashcards in StudyCat.
Big ideas
- Inheritance:
class Dog(Animal):makes Dog a kind of Animal. Dog gets every attribute and method of Animal and can add or replace some. - Overriding: define a method with the same name in the subclass to replace it. Call the parent version with
super().method(), especiallysuper().__init__(...)to set up inherited attributes. isinstance(d, Animal)is True for a Dog. Python looks for a method on the object’s class first, then its parents.- Class attributes (defined in the class body) are shared by all objects; instance attributes (
self.x) belong to one object. A class attribute is handy for counting objects. - Composition: an object can hold other objects (a Course holds a list of Students). Prefer “has a” (composition) unless something really “is a” (inheritance).
Code you should know
Subclass, override, super
class Animal:
count = 0
def __init__(self, name):
self.name = name
Animal.count += 1
def speak(self):
return "..."
def describe(self):
return f"{self.name} says {self.speak()}"
class Dog(Animal):
def speak(self):
return "Woof"
class Puppy(Dog):
def __init__(self, name, age_weeks):
super().__init__(name)
self.age_weeks = age_weeks
def speak(self):
return super().speak() + "!"
pets = [Animal("Rock"), Dog("Rex"), Puppy("Bit", 8)]
for p in pets:
print(p.describe())
print(Animal.count, isinstance(pets[2], Dog), isinstance(pets[1], Puppy))Output
Rock says ... Rex says Woof Bit says Woof! 3 True False
Composition: objects inside objects
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
class Course:
def __init__(self, title):
self.title = title
self.students = []
def add(self, student):
self.students.append(student)
def average(self):
return sum(s.score for s in self.students) / len(self.students)
def top(self):
return max(self.students, key=lambda s: s.score).name
c = Course("CSCI 127")
c.add(Student("Ana", 91))
c.add(Student("Ben", 84))
print(c.title, len(c.students), c.average(), c.top())Output
CSCI 127 2 87.5 Ana
Worked example
What does this print?
class A:
def hi(self):
return "A"
class B(A):
def hi(self):
return "B" + super().hi()
class C(B):
pass
print(C().hi(), isinstance(C(), A))Show the solution
BA True. C has no hi, so B’s runs; it adds "B" to A’s result. Every C is a B, and every B is an A.Common mistakes
- Forgetting
super().__init__(), so inherited attributes never get set (AttributeError later). - Modifying a class attribute through
self.count += 1, which creates an instance attribute instead. - Using inheritance for “has a” relationships.
Exam tipBe ready to write a small class hierarchy on paper and to state, for a given call, which class’s method runs.
Keep going in StudyCat
StudyCat is free for Montana State students: an endless quizzer with worked explanations, one-question lessons, flashcards, exam prep checklists, the class calendar with every deadline, a grade calculator and a study board for CSCI 127.