Every value in Python is an object: a bundle of data with the operations that go with it. "hi" is a str object with methods like upper(); a list is an object with append(). A class is the blueprint for a kind of object, and with class you can make your own.
Say a game needs ducks, each with a name and some energy. You could keep separate variables or dicts, but a class keeps each duck's data and the things a duck can do together.
class Duck:
def __init__(self, name, energy=10):
self.name = name
self.energy = energy
def swim(self, minutes):
self.energy -= minutes
return f"{self.name} swam for {minutes} minutes"
d = Duck("Dot")
print(d.swim(3))
print(d.energy)
Prints
Dot swam for 3 minutes
7
Step by step: Duck("Dot") makes a new duck object, called an instance of the class, and Python calls its __init__ method to set it up. self is the object being worked on: self.name = name stores the name on this particular duck. Data stored like that is an attribute, and functions defined in the class are methods. When you call d.swim(3), Python passes d as self for you.
Each instance has its own attributes, so two ducks don't share energy:
class Duck:
def __init__(self, name):
self.name = name
self.energy = 10
a = Duck("Ana")
b = Duck("Bo")
a.energy -= 4
print(a.energy, b.energy)
Prints
6 10
Printing an object normally shows something unhelpful like <__main__.Duck object at 0x7f...>. Define __str__ to choose what print() and str() show. Methods with double underscores on both sides are called special methods (or dunder methods); Python calls them itself at the right moments.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"({self.x}, {self.y})"
def moved(self, dx, dy):
return Point(self.x + dx, self.y + dy)
p = Point(1, 2)
print(p)
print(p.moved(3, 0))
Prints
(1, 2)
(4, 2)
Class names are written in CapitalisedWords (Duck, ShoppingCart) to tell them apart from functions and variables. Use a class when some data and the functions that work on it belong together; for a loose bundle of values a dict is often enough. The advanced course goes further: inheritance, more special methods and dataclasses.
Practice
What does this print?
class Counter:
def __init__(self):
self.n = 0
def tick(self):
self.n += 1
c = Counter()
c.tick()
c.tick()
print(c.n)
More info
Quick reference
class Name:
Defines a new kind of object (a blueprint).
__init__(self, ...)
Sets up a new instance; called by Name(...).
self.attr = value
An attribute: data stored on this instance.
def method(self, ...):
A function that belongs to the class; called as obj.method(...).