Your first class
Last updated
Python comes with classes like str and list. Now you'll write one of your own. In this lesson you'll see what goes wrong with books kept as dicts, write a Book class, set each book up with __init__ and self, give books methods, read the error you get when a method forgets self, and make a whole catalogue of books from one class.
By the end of this lesson you can
- Write a class with
__init__, and make objects from it - Read and change an object's attributes through
selfand through a name - Write methods, and read the error when a method forgets
self - Keep many objects of one class in a list and loop over them
Why dicts aren't enough
In the 2.P project each book was a dict. That works, but nothing says what a book must have, or what's allowed. Run this.
Three things went wrong, and Python only noticed the last one:
- Line 2 gave Dune
-1copies. Nothing stopped it. - Line 3 misspelt
"title"as"titel", and left outcopies. Nothing stopped that either. - The program only failed on line 6, when it read the misspelt book, far from the line with the typo.
A class fixes this. It's a description of what every book has and what every book can do, written once. Each book made from it, called an object or an instance, is set up the same way.
class Book, __init__ and self
class Book: starts a new class. Class names use CapitalWords, so they stand out from other names. Everything indented under it belongs to the class.
__init__, with two underscores on each side, is a method Python runs every time a new book is made. Its job is to set the book up. Its first parameter, self, is the new book itself. The others are the values you pass in.
To make a book, call the class like a function: Book("Dune", "Frank Herbert", 2). Python makes an empty book, runs __init__ with that book as self and your three values after it, and gives you the finished book.
Watch it run. Python jumps from line 8 into __init__, and the values table shows self filling up, one attribute at a time. When __init__ ends, the book gets the name dune.
type(dune) says it's a Book. __main__ is the name of the file being run, as in lesson 2.7.
Attributes
self.title = title makes an attribute: a name that belongs to one object. Outside the class you reach it through the object's name, dune.title. Inside a method you reach it through self. It's the same attribute either way.
Attributes can be read and changed like any other name. Line 9 adds a copy.
vars(dune) on line 11 shows the book's attributes. They're kept in a dict, much like the dicts in 2.P, but now the class decides what goes in it.
Try a typo: change line 10 to read dune.titel. Python stops with an AttributeError, and it guesses what you meant.
Methods
A function written inside a class is a method. Every method takes self first, the book it was called on, so it can use that book's attributes.
describe gives back a line about the book. lend takes a copy off the shelf, unless there are none left.
dune.describe() on line 18 calls describe with dune as self. You don't pass self yourself: the object before the dot is passed for you. Watch it run, and see self in the values table while each method runs.
Data and the code that works on it now live together. Anything that wants to lend a book calls lend, and the rule about zero copies is in one place.
A method that forgot self
Here describe was written without self in its brackets. Run it.
The last line of the traceback says describe() takes 0 positional arguments but 1 was given. But line 11 passes nothing! That's the clue: dune.describe() is really Book.describe(dune). Python always passes the object before the dot as the first value, and this describe has no name to take it.
Put self back on line 6, def describe(self):, and run it again.
Many objects, one class
One class can make as many objects as you like. Each has its own attributes, and they all share the class's methods.
A list of books works like any list: loop over it, and read each book's attributes in a comprehension (line 18). Watch it run. The values table shows each book as Book object: with its attributes. That's how this page shows an object. Lesson 3.5 shows how to choose what Python itself prints for one.
Add a fourth book to the list, and run it again.
In other languages
This step is optional. It's for anyone who will meet Java or Rust later.
| Python | Java | Rust | |
|---|---|---|---|
| Making an object | Book("Dune", 2) | new Book("Dune", 2) | Book::new("Dune", 2), or Book { title: …, copies: 2 } |
| Setting it up | def __init__(self, …) | A constructor with the class’s own name | A function called new, by custom |
| Which attributes it has | Whatever __init__ sets. More can be added later | Listed in the class, each with a type. No more can be added | Listed in the struct, each with a type. No more can be added |
| The object itself, in a method | self, written first in every method | this, there without being written | &self or &mut self, written first |
Rust has no classes, but a struct with methods does the same job. Simple Rust 2.1 builds one, and it writes self out just as Python does.
Check what you learned
Three questions. Pick or type an answer, then check it.
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- The Python Tutorial: A First Look at Classes: class definitions, class objects, instance objects and method objects
- The Python Tutorial: Random Remarks: why the first parameter is called self
- The Python Language Reference: Class definitions
- The Python Language Reference: object.__init__
- Built-in Functions: vars
- PEP 8: Class Names: CapWords for classes
- The Java Tutorials: Classes: fields, constructors and methods in a Java class
- The Java Tutorials: Using the this Keyword: the object itself in a Java method
- The Rust Programming Language: Defining and Instantiating Structs: a Rust struct holds the data
- The Rust Programming Language: Method Syntax: methods in an impl block, with self