MathubLearn / Practice / Excel
CSCI 127 Joy and Beauty of Data · Unit 3: Object-oriented programming · on Exam 2

3.3 OOP principles

Study notes for OOP principles 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 Mathub.

Big ideas

Code you should know

Polymorphism in a loop
class Shape:
    def area(self):
        return 0
    def __str__(self):
        return f"{type(self).__name__} with area {self.area():.1f}"

class Rect(Shape):
    def __init__(self, w, h):
        self.w, self.h = w, h
    def area(self):
        return self.w * self.h

class Circle(Shape):
    def __init__(self, r):
        self.r = r
    def area(self):
        return 3.14159 * self.r ** 2

shapes = [Rect(3, 4), Circle(1), Rect(2, 2)]
for s in shapes:
    print(s)
print("total", round(sum(s.area() for s in shapes), 1))
Output
Rect with area 12.0
Circle with area 3.1
Rect with area 4.0
total 19.1
Encapsulation with a guarded setter
class Thermostat:
    def __init__(self):
        self._target = 68

    def get_target(self):
        return self._target

    def set_target(self, degrees):
        if 50 <= degrees <= 90:
            self._target = degrees
        else:
            print("ignored", degrees)

t = Thermostat()
t.set_target(72)
t.set_target(120)
print(t.get_target())
Output
ignored 120
72

Worked example

A program has Car, Truck and Bicycle objects in one list and calls v.describe() on each. Which principle makes that work, and what must be true of the three classes?
Show the solution
Polymorphism: each class defines its own describe method with the same name, so one loop works for all of them. They may share a parent (Vehicle) but in Python they only need the method.

Common mistakes

Exam tipExam 2 usually has a short-answer question on these principles. Have a two-sentence answer with a code-flavored example ready for each.

Keep going in Mathub

Mathub 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.