Classes and objects · lesson 2 of 7
Parts in this lesson
Aclass Book:a new kind of object
Bdef __init__(self, …)sets up each new book
Cself.titlean attribute
Ddef describe(self)a method
EBook("Dune", …)make a book

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 self and 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.

Step 1 code main.py
Edit the code, then run it again

Three things went wrong, and Python only noticed the last one:

  • Line 2 gave Dune -1 copies. Nothing stopped it.
  • Line 3 misspelt "title" as "titel", and left out copies. 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.

Step 2 code main.py
Edit the code, then run it again

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.

Step 3 code main.py
Edit the code, then run it again

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.

Step 4 code main.py
Edit the code, then run it again

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.

Step 5 code main.py
Edit the code, then run it again

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.

Step 6 code main.py
Edit the code, then run it again

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.

A class in three languages
PythonJavaRust
Making an objectBook("Dune", 2)new Book("Dune", 2)Book::new("Dune", 2), or Book { title: …, copies: 2 }
Setting it updef __init__(self, …)A constructor with the class’s own nameA function called new, by custom
Which attributes it hasWhatever __init__ sets. More can be added laterListed in the class, each with a type. No more can be addedListed in the struct, each with a type. No more can be added
The object itself, in a methodself, written first in every methodthis, 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.

What does this program print?
class Shelf:
    def __init__(self, name):
        self.name = name
        self.books = 0

    def add(self):
        self.books += 1


a = Shelf("A")
b = Shelf("B")
a.add()
a.add()
b.add()
print(a.books)
When does __init__ run?
dune.describe() runs def describe(self):. What is self while it runs?

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.

All sources for Simple Python