After this lesson you can pick the right kind of method for a job and write a class method that builds objects from text.
Three kinds of method
Every method you have written so far was an instance method: it starts with self and works on the data of one object. Python has two other kinds, and they differ in what they receive automatically.
| Kind | Marked with | First parameter | Typical use |
|---|---|---|---|
| Instance method | nothing | self (the object) |
Work with one object's data |
| Class method | @classmethod |
cls (the class) |
Work with the class as a whole, make objects |
| Static method | @staticmethod |
nothing extra | A helper that needs neither |
The @ lines are decorators, which you will learn about properly later. For now, just write the marker on the line above def.
Instance methods
This is the familiar kind. Here it is on a library book:
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
self.is_borrowed = False
def borrow(self):
self.is_borrowed = True
def status(self):
return f"{self.title}: {'out' if self.is_borrowed else 'in'}"
novel = Book("The Silent Garden", 320)
print(novel.status())
novel.borrow()
print(novel.status())The Silent Garden: in
The Silent Garden: outClass methods
A class method receives the class instead of an object. That is useful when the work is not about one particular book. A very common job is an alternative constructor: another way to create an object, such as from a line of text.
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
@classmethod
def from_text(cls, text):
title, pages = text.split(";")
return cls(title.strip(), int(pages))
def describe(self):
return f"{self.title} ({self.pages} pages)"
book = Book.from_text("Night Trains; 180")
print(book.describe())
print(type(book))Night Trains (180 pages)
<class '__main__.Book'>Inside from_text, cls is the class Book, so cls(...) is the same as Book(...). You call the method on the class, with no object needed, because there is no object yet. Writing cls(...) instead of the hard-coded Book(...) pays off with inheritance, which is two lessons away: a subclass calling from_text would get an object of the subclass.
Class methods can also read and change class attributes:
class Library:
name = "Town Library"
loan_days = 14
@classmethod
def set_loan_days(cls, days):
cls.loan_days = days
Library.set_loan_days(21)
print(Library.loan_days)21Static methods
A static method gets nothing automatic. It is an ordinary function that happens to live inside the class because it belongs with the topic:
class Isbn:
@staticmethod
def is_valid_length(code):
digits = code.replace("-", "")
return len(digits) in (10, 13)
print(Isbn.is_valid_length("978-0-12-345678-9"))
print(Isbn.is_valid_length("12345"))True
FalseIf you find yourself writing a static method, ask whether it should simply be a normal function in the module. Often it should. Static methods are a matter of organisation, not necessity.
How to choose
Ask what the method needs:
- It needs one object's data: use an instance method.
- It needs the class, for example to create objects or change shared data: use a class method.
- It needs neither: use a static method, or a plain function.
You can call any of the three through an object too, and Python still passes the right thing. Compare:
print(book.describe())
print(Book.describe(book))Night Trains (180 pages)
Night Trains (180 pages)The second line shows what self really is: calling through the class and passing the object yourself is exactly what Python does for you in the first line.
A video version of this topic is in the video course at /learn/python/.
Common mistakes
- Forgetting the decorator. Without
@classmethod, a method written withclsreceives an object, not the class. - Forgetting
selfin an instance method. Calling it then fails with aTypeErrorabout arguments. - Using
selfinside a class or static method. Those have no object, soselfis not defined there. - Hard-coding the class name in an alternative constructor. Use
cls(...)so subclasses work. - Making everything static. If a method needs the object's data, make it an instance method.
Exercise
Write a class Product with name and price. Add a class method from_text that accepts text such as "Pen,2.5" and returns a product, and a static method is_positive(price) that returns whether a price is above zero. Build a product from "Pen,2.5" and print its name, its price and the result of Product.is_positive(-1).
Show one possible answer
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
@classmethod
def from_text(cls, text):
name, price = text.split(",")
return cls(name, float(price))
@staticmethod
def is_positive(price):
return price > 0
pen = Product.from_text("Pen,2.5")
print(pen.name, pen.price)
print(Product.is_positive(-1))Pen 2.5
FalseKey points
- An instance method takes self and works with one object's data. It is the normal kind.
- A class method is marked with @classmethod, takes cls, and works with the class itself.
- A static method is marked with @staticmethod, takes neither self nor cls, and is just a function stored inside the class.
- A common use of class methods is an alternative constructor, such as Book.from_text(...).
- Because class methods receive cls, they keep working correctly in subclasses.