Sub topic 5
Classmethods and staticmethods
This chapter assumes you can write a class with __init__ and instance methods. It also assumes you know the difference between instance attributes and class attributes. Here you will learn two other kinds of method, when each fits, and the mistakes people make with them.
Three kinds of method
An instance method receives the instance as its first argument, self. A classmethod receives the class, by convention named cls. A staticmethod receives nothing automatically.
| Kind | Decorator | First argument | Can reach instance state | Can reach class state |
|---|---|---|---|---|
| Instance method | none | `self` | yes | yes, through `self.__class__` |
| Classmethod | `@classmethod` | `cls` | no | yes |
| Staticmethod | `@staticmethod` | none | no | no |
Classmethods as alternative constructors
Python allows only one __init__ per class. A classmethod lets you offer other named ways to build an instance.
class Pizza:
def __init__(self, toppings):
self.toppings = list(toppings)
@classmethod
def margherita(cls):
return cls(["mozzarella", "basil"])
@staticmethod
def is_valid_topping(name):
return name.isalpha()
p = Pizza.margherita()
print(p.toppings) # ['mozzarella', 'basil']
print(Pizza.is_valid_topping("ham")) # TruePizza.margherita() calls Pizza with the toppings list. The class is passed in automatically, so cls is Pizza here.
Why use `cls` instead of the class name
Inside a classmethod, write cls(...), not Pizza(...). Then a subclass that inherits the method builds an instance of the subclass.
class Pizza:
def __init__(self, toppings):
self.toppings = list(toppings)
@classmethod
def margherita(cls):
return cls(["mozzarella", "basil"])
class StuffedPizza(Pizza):
pass
print(type(StuffedPizza.margherita()).__name__) # StuffedPizzaIf margherita had hard-coded Pizza(...), the result would be a plain Pizza. That would silently lose any behavior the subclass adds.
Parsing input with a classmethod
A common use is converting data from another format.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
@classmethod
def from_string(cls, text):
x, y = text.split(",")
return cls(int(x), int(y))
pt = Point.from_string("3,4")
print(pt.x, pt.y) # 3 4Staticmethods
A staticmethod is an ordinary function that lives in the class namespace. It cannot see self or cls. Use it for a helper that is related to the class but needs neither. The is_valid_topping method above is an example.
You can call both kinds on the class or on an instance. Pizza.is_valid_topping("ham") and p.is_valid_topping("ham") behave the same.
Common errors
- Forgetting the decorator. Without
@classmethod, the first parameter is bound to the instance. Called on the class, the method raises aTypeErrorabout a missing argument. - Using
selfin a staticmethod. The nameselfis just an ordinary parameter there. Calling the method then fails because nothing supplies that argument. - Hard-coding the class name. This breaks subclass support, as shown above.
- Expecting a classmethod to see instance attributes. It has no instance. Only class attributes are reachable through
cls.
Choosing between them
- If the method needs the instance's data, make it an instance method.
- If it needs the class, for example to construct instances or read class-level settings, make it a classmethod.
- If it needs neither, make it a staticmethod, or a plain function.
Exercise
Add a classmethod from_celsius_string to a Temperature class whose __init__ takes a number of degrees. It should accept text like "21.5C" and return an instance. Why use cls rather than Temperature in the body?
Show answer
Define @classmethod def from_celsius_string(cls, text): return cls(float(text.rstrip("C"))). Using cls means a subclass of Temperature that calls the method gets an instance of the subclass, not a base Temperature.
Exercise
A method uses neither self nor cls, and only checks whether a string is all digits. Which kind of method fits, and what is a reasonable alternative?
Show answer
A staticmethod fits. A plain module-level function is an equally good alternative if the helper is not closely tied to the class.