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
- A class is a blueprint; an object (instance) is one thing built from it:
p = Point(3, 4). Each object has its own attributes (data) and shares the class’s methods (functions). __init__(self, ...)runs when an object is created and sets its attributes withself.x = x.selfis the object the method is working on; Python passes it automatically.- Methods are called with a dot:
p.move(1, 2). Inside,self.xreads or changes that object’s state, so calling a method can change the object. __str__(self)returns the textprint(p)shows. Other special methods:__eq__for==,__lt__for sorting.- Objects can be stored in lists and dictionaries and passed to functions. A list of objects plus a loop is the heart of most programs.
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
- Forgetting
selfin the method definition or writingx = xinstead ofself.x = xin__init__. - Calling
Point.move(1, 2)on the class instead of on an object. - Returning a string from
__str__with print inside it, or forgetting the return. - Sharing a mutable default such as a list between objects.
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.