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

3.1 Classes and objects: the basics

Study notes for Classes and objects: the basics 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

A class with state and behavior
class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount

    def withdraw(self, amount):
        if amount > self.balance:
            return False
        self.balance -= amount
        return True

    def __str__(self):
        return f"{self.owner}: ${self.balance:.2f}"

acct = BankAccount("Nik", 50)
acct.deposit(25)
print(acct.withdraw(100), acct.withdraw(30))
print(acct)
print(acct.balance, acct.owner)
Output
False True
Nik: $45.00
45 Nik
Many objects, one class
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def distance_to(self, other):
        return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5

    def __str__(self):
        return f"({self.x}, {self.y})"

points = [Point(0, 0), Point(3, 4), Point(6, 8)]
for p in points:
    print(p, p.distance_to(points[0]))
print(points[1].x + points[2].y)
Output
(0, 0) 0.0
(3, 4) 5.0
(6, 8) 10.0
11

Worked example

What does this print?
class Counter:
    def __init__(self):
        self.n = 0
    def tick(self):
        self.n += 1
        return self.n

a = Counter()
b = Counter()
a.tick(); a.tick()
print(a.tick(), b.tick(), a.n + b.n)
Show the solution
3 1 4. Each object keeps its own n; a has been ticked three times, b once.

Common mistakes

Exam tipFor exam questions, draw one box per object with its attributes and update the boxes as methods run. Write the class skeleton (class, __init__, __str__) from memory.

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.