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
@classmethodthat 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.
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_daysgivesemmaan attribute of her own, which hides the class's. Line 15 shows it: onlyemmahasloan_daysin 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.
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.
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.
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.
__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.
| Written | Gets first | Use it for | |
|---|---|---|---|
| Ordinary method | def lend(self): | The object, self | Anything about one book: dune.lend() |
| Class method | @classmethoddef from_csv_row(cls, row): | The class, cls | Making objects another way: Book.from_csv_row(row) |
| Static method | @staticmethoddef is_isbn(text): | Nothing extra | A 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.
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.
| Python | Java | Rust | |
|---|---|---|---|
| Data shared by the class | A class attribute: loan_days = 14 in the class | A static field | A constant in the impl block: const LOAN_DAYS: u32 = 14; |
| Another way to make an object | @classmethod, which gets cls | A static method that calls new, or a second constructor | A function in the impl block with no self, like Book::new |
| A helper with no object | @staticmethod | A static method | A function in the impl block with no self |
| Calling it | Book.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.
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: Class and Instance Variables: including the shared list mistake
- Built-in Functions: classmethod
- Built-in Functions: staticmethod
- Glossary: decorator: what the @ line does
- The Python Standard Library: csv.DictReader
- The Java Tutorials: Understanding Class Members: static fields and methods in Java
- The Rust Programming Language: Associated Functions: Rust functions on a type with no self, like String::from
- The Rust Programming Language: Constants: values fixed for the whole program in Rust