StudyCatLearn / Practice / Excel
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

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

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.