Classes and objects
Overview
You’ve used plenty of objects already: strings have .upper(), lists have .append(), files have .read(). Each is an object of some type (or class) that bundles data with behaviour. Now you’ll create your own types. Classes are how larger programs model the things they deal with: users, orders, accounts, game characters.
Why classes?
Suppose you track dogs with dictionaries and functions:
rex = {"name": "Rex", "age": 3}
def describe(dog):
return f"{dog['name']} is {dog['age']}"It works, but nothing connects the functions to the data they expect, typos in keys only show up at run time, and every function has to be passed the dict. A class packages the data and the functions that operate on it into one unit.
Defining a class
class Dog:
"""A dog with a name and an age."""
def __init__(self, name, age):
self.name = name
self.age = age
def speak(self):
return f"{self.name}: Woof!"
def birthday(self):
self.age += 1class Dog:starts the definition. Class names use CapWords (Dog,TodoList,BankAccount).- Functions inside a class are methods.
__init__is a special method that Python calls automatically to set up each new object.
Creating objects
Call the class like a function to create an instance:
rex = Dog("Rex", 3)
bella = Dog("Bella", 7)
print(rex.name) # Rex
print(bella.speak()) # Bella: Woof!
rex.birthday()
print(rex.age) # 4
print(bella.age) # 7 — bella is unaffectedDog("Rex", 3) creates a new, empty object, then calls __init__(that_object, "Rex", 3). Each object stores its own data.
self
Every method’s first parameter is self: the particular object the method was called on. When you write rex.speak(), Python effectively calls Dog.speak(rex) — so inside speak, self is rex.
self.name = namein__init__creates an attribute on that object.self.age += 1inbirthdaychanges the age of whichever dog it was called on.
Forgetting self is the classic beginner mistake:
class Dog:
def speak(): # missing self
return "Woof"
Dog().speak()TypeError: Dog.speak() takes 0 positional arguments but 1 was givenThe “1 given” is the object itself, passed automatically.
Attributes
Attributes are read and set with a dot:
rex.age = 5 # change it from outside
rex.owner = "Asha" # you CAN add new attributes like this — but don'tDefine all attributes in __init__, so every object has the same shape and readers can see the full list in one place. Use None or an empty collection for things that start unknown or empty:
def __init__(self, owner):
self.owner = owner
self.tasks = [] # each object gets its own new listPrivate by convention
Python has no truly private attributes. A leading underscore — self._balance — signals “internal: please don’t touch from outside”. Other programmers respect it; Python doesn’t enforce it.
Class attributes
A variable assigned in the class body (not on self) is shared by all instances:
class Dog:
species = "Canis familiaris" # same for every dog
def __init__(self, name):
self.name = name # different for every dog
Dog.species # 'Canis familiaris'
Dog("Rex").species # 'Canis familiaris'Use class attributes for constants. Don’t use a mutable class attribute like tasks = [] for per-object data — it would be shared, just like the mutable default trap in Parameters and arguments.
Methods that keep objects valid
Methods are the place to enforce rules about the data:
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("deposit must be positive")
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
raise ValueError("insufficient funds")
self.balance -= amountIf all changes go through deposit and withdraw, the balance can never become negative.
Printing objects
print(rex) # <__main__.Dog object at 0x7f…>Not very helpful! The next lesson, Special methods, shows how to give objects readable text — and how to make them work with ==, <, len() and more.
When to write a class
- You have data and functions that always go together (an account and its deposit/withdraw).
- You need many objects of the same shape (players, products, orders).
- The thing has state that changes over time (a game character’s health).
For a few lines of logic, plain functions are simpler. For records that mostly hold data, Dataclasses saves a lot of typing.
Remember: the class is the blueprint, objects are built from it,
__init__sets up each object, andselfis the object a method is working on.
A to-do list class
Write a TodoList class. __init__(self, owner) stores the owner and starts with an empty list of tasks. Each task is a dict with title and done. Add methods: add(title) appends a task that isn’t done; complete(title) marks the matching task done and raises ValueError if there’s no such task; pending() returns the titles not yet done; summary() returns a string like Asha: 1 of 3 done. Create two lists for two people, add and complete some tasks, and print summaries and pending tasks to show that each object keeps its own data.
class TodoList:
def __init__(self, owner):
...
def add(self, title):
...
def complete(self, title):
...
def pending(self):
...
def summary(self):
...class TodoList:
"""A person's list of tasks."""
def __init__(self, owner):
self.owner = owner
self.tasks = []
def add(self, title):
self.tasks.append({"title": title, "done": False})
def complete(self, title):
for task in self.tasks:
if task["title"] == title:
task["done"] = True
return
raise ValueError(f"no task called {title!r}")
def pending(self):
return [t["title"] for t in self.tasks if not t["done"]]
def summary(self):
done = sum(1 for t in self.tasks if t["done"])
return f"{self.owner}: {done} of {len(self.tasks)} done"
asha = TodoList("Asha")
ben = TodoList("Ben")
asha.add("Buy milk")
asha.add("Write report")
asha.add("Call mum")
ben.add("Fix bike")
asha.complete("Write report")
print(asha.summary()) # Asha: 1 of 3 done
print(ben.summary()) # Ben: 0 of 1 done
print(asha.pending()) # ['Buy milk', 'Call mum']
try:
ben.complete("Swim")
except ValueError as error:
print("Error:", error) # Error: no task called 'Swim'Summary
- A class is a blueprint for a new type; calling it —
Dog("Rex", 3)— creates an object (an instance). __init__sets up each new object; it stores data in attributes such asself.name.- Methods are functions defined in the class; their first parameter,
self, is the object they were called on. - Each object has its own attribute values, while methods are shared by all objects of the class.
- Use classes to keep related data and the functions that work on it together.