A class is a type you define. An object is one instance. self is that instance inside a method. This is a light pass — enough to read and write a small class.
Goal
Define __init__, a method, and two instances.
A record with behavior
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
def passed(self, mark=90):
return self.score >= mark
def label(self):
return f"{self.name}: {self.score}"
ada = Student("Ada", 98)
alan = Student("Alan", 88)
print(ada.label())
print(ada.passed(), alan.passed())
print(ada.name, ada.score)__init__ runs on Student(...). Attributes live on self.
Methods vs functions
class Counter:
def __init__(self):
self.n = 0
def bump(self, step=1):
self.n += step
return self.n
c = Counter()
print(c.bump())
print(c.bump(4))
print(c.n)__str__
class City:
def __init__(self, name, region):
self.name = name
self.region = region
def __str__(self):
return f"{self.name} ({self.region})"
print(City("Nairobi", "Central"))
print(City("Mombasa", "Coast"))Without __str__, print shows a default <City object ...>.
Tip
Start with dicts and functions. Promote to a class when several functions all take the same bundle of fields.