Classes and objects · lesson 4 of 7
Parts in this lesson
Aloan_days = 14a class attribute
BBook.made += 1change it on the class
C@classmethodgets the class, cls
D@staticmethodgets neither

Class attributes, class methods and static methods

Last updated

So far every attribute has belonged to one object. Some things belong to the whole class: how many days every loan lasts, or how many books have been made. In this lesson you'll keep data on the class itself, count objects as they're made, add a second way to make a book, straight from a row of a CSV file, write a helper that belongs with books but needs no book, and meet the list that every member ends up sharing.

By the end of this lesson you can

  • Tell an instance attribute from a class attribute, and say which one Python finds first
  • Count objects with a class attribute
  • Write a @classmethod that makes objects another way
  • Write a @staticmethod, and say when to use each kind of method

Instance or class attribute

Every book in this library can be borrowed for 14 days. That isn't a fact about one book. It's a fact about all books, so it's written once in the class body, outside any method. That makes a class attribute. The attributes set on self in __init__ are instance attributes: each book has its own.

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

When you read dune.loan_days, Python looks in dune's own attributes first. dune has no loan_days of its own, so Python looks in the class next, and finds 14.

  • Line 11 changes the class attribute, and every book sees 21.
  • Line 13 is different. Setting emma.loan_days gives emma an attribute of her own, which hides the class's. Line 15 shows it: only emma has loan_days in her own attributes.

To change something shared, change it on the class: Book.loan_days = 21.

Counting objects

A class attribute can count objects as they're made. made starts at 0, and __init__ adds 1 to it every time a book is made, then gives the book that number.

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

Line 5 writes Book.made, not self.made. Reading through self would work, but self.made += 1 sets the attribute through self, so each book would get its own made and the class's count would stay at 0, the same trap as emma.loan_days. Change line 5 to self.made += 1 and line 7 to self.number = self.made, run it, and see every book come out as number 1.

@classmethod: another way to make a book

In 2.P, books came from a CSV file, where every value is text. Making a Book from a row means picking out the values and turning the year into a number. That job belongs with Book, so it goes in the class, as a second way to make a book.

@classmethod, on the line above a method, is a decorator: it changes how the method works. A class method gets the class as its first value, by custom called cls, instead of an object. cls(...) is the same as Book(...), so it makes a book and runs __init__ as usual.

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

You call it on the class: Book.from_csv_row(row). Line 18 shows the year is a number now. The row has a copies key too, which from_csv_row ignores.

Here it is with the CSV file from 2.P. A comprehension makes a book from every row.

Step 3 code
Edit the code, then run it again

Names like from_csv_row that start with from_ are the usual way to say "another way to make one". Python's own dict.fromkeys and datetime.date.fromisoformat are class methods too.

@staticmethod

Some helpers belong with books but need neither a book nor the class. Checking whether some text looks like an ISBN, the 13-digit number on every book, is one. A static method gets no self and no cls, only the values you pass it.

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

__init__ uses Book.clean_isbn on line 4, so every book's ISBN is stored without hyphens or spaces. And Book.is_isbn can check some text before any book exists, as on lines 16 and 17.

A static method is a plain function that lives in the class, because that's where someone would look for it. Here are the three kinds of method side by side.

Three kinds of method
WrittenGets firstUse it for
Ordinary methoddef lend(self):The object, selfAnything about one book: dune.lend()
Class method@classmethod
def from_csv_row(cls, row):
The class, clsMaking objects another way: Book.from_csv_row(row)
Static method@staticmethod
def is_isbn(text):
Nothing extraA helper that belongs with books but needs no book: Book.is_isbn(text)

One list for every member

Here a member's loans are kept in a list. Sam borrows Dune, and Ana borrows nothing. Run it and look at Ana's loans.

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

It's the shared default list from lesson 2.5 again, in a new place. Class attributes are fine for values that never change, like loan_days = 14, or that you change on purpose through the class. A list, dict or set that each object fills up belongs in __init__.

In other languages

This step is optional. It's for anyone who will meet Java or Rust later.

Class-level members in three languages
PythonJavaRust
Data shared by the classA class attribute: loan_days = 14 in the classA static fieldA constant in the impl block: const LOAN_DAYS: u32 = 14;
Another way to make an object@classmethod, which gets clsA static method that calls new, or a second constructorA function in the impl block with no self, like Book::new
A helper with no object@staticmethodA static methodA function in the impl block with no self
Calling itBook.from_csv_row(row)Book.fromCsvRow(row)Book::from_csv_row(row)

In Java and Rust, a value written once for the whole class can't be hidden by one object, as emma.loan_days did in step 1. Simple Rust 2.1 writes Song::new the Rust way.

Check what you learned

Three questions. Pick or type an answer, then check it.

What does this program print?
class Book:
    loan_days = 14


dune = Book()
emma = Book()
dune.loan_days = 7
print(emma.loan_days)
What does a @classmethod get as its first value?
Every new Member needs an empty list of loans. Where does loans = [] go?

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