8 min read
Classes and objects
From a list of steps to a set of things
So far your programs have mostly been lists of instructions: do this, then that, then loop over the other. That works well until a program grows and everything starts touching everything else, so that a change in one corner quietly breaks something far away. Object-oriented programming is a different way to organise the same work. Instead of one long recipe, you describe the things in your program and what each thing can do, then let them interact.
A "thing" here might be a book, a bank account, a bus ticket, or a player in a game. The point of the style is to keep each thing's data and behaviour bundled together in one place, so the rest of the program does not have to reach inside and meddle.
A class is a blueprint
A class is the blueprint for a kind of thing. It does not store any particular book; it describes what every book will have and what every book can do. From one blueprint you can build many actual items, and each built item is called an object, or an instance of the class.
Think of the blueprint for a house versus the houses on a street. There is one blueprint, but ten houses, each with its own address and colour. The blueprint is the class; each house is an object.
Here is a small class describing a book.
class Book:
def __init__(self, title, pages):
self.title = title # this object's own title
self.pages = pages # this object's own page count
def summary(self):
return f"'{self.title}' has {self.pages} pages"
The __init__ method runs automatically whenever a new book is created. Its job is to set up that object's starting data. The word self always means "this particular object", so self.title is the title belonging to the one book you are building, not to books in general.
Making objects
With the blueprint written, you can build as many books as you want. Each call to Book(...) produces a brand new object with its own data.
first = Book("The Long Road", 240)
second = Book("Quiet Mornings", 96)
print(first.summary()) # 'The Long Road' has 240 pages
print(second.summary()) # 'Quiet Mornings' has 96 pages
print(first.pages) # 240
Notice that first and second are independent. They came from the same class, but changing one does not touch the other, because each carries its own title and pages. That independence is exactly what keeps large programs from tangling: each object minds its own data.
Tip
When you read self inside a class, mentally replace it with "the specific object this is running on". self.pages is not "all pages everywhere", it is "the pages of the one book we are dealing with right now". That single habit clears up most early confusion about classes.
Why bother
For a five line script, classes are overkill, and you should not force them. Their value shows up when a program has several things that each carry state and behaviour, and when you want to add more of them later without rewriting everything. Bundling the data and the actions that belong to it into one blueprint means the rest of your code can say "make me a book" and "give me its summary" without ever needing to know how a book stores its pages. The next lessons build on this: what exactly lives inside an object, and how objects can borrow behaviour from one another.
Prefer to see it explained? Here is the recorded Code for Albania lecture on this topic.
Try this now
Write a small class Dog with an __init__ that stores name and breed, and a method describe() that returns a sentence using both. Build two different dogs and print each one's description. Change one dog's name and confirm the other dog is unaffected.
Check yourself
- In your own words, what is the difference between a class and an object? Use the house blueprint comparison to explain it.
- What does the
__init__method do, and when does Python run it? Why does it takeselfas its first parameter? - After
first = Book("A", 10)andsecond = Book("B", 20), you changefirst.pagesto11. Doessecond.pageschange? Explain what that tells you about how objects hold their data.
Where this lesson comes from
Built from
- Data Structures and Algorithms
alphaPlan courses are built from taught programmes rather than invented for the web. Where a claim rests on an outside standard or a reported case, it is named above so you can check it rather than take our word for it.
This course was developed by alphaPlan Center from programs delivered in partnership with the American Corners network.
Found something unclear, outdated or improvable? Suggest an improvement