Sub topic 4
Static methods: functions that live in a class namespace
This chapter assumes you can define classes and instance methods, know what self is, and recognize @name decorator syntax above a function. It also assumes you know the difference between class attributes and instance attributes.
What a static method is
A static method is an ordinary function stored inside a class. Python passes it no automatic first argument. It receives neither self (the instance) nor cls (the class). It gets exactly the arguments you give it.
You create one by placing @staticmethod above a def inside the class body.
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
@staticmethod
def is_valid(celsius):
return celsius >= -273.15
print(Temperature.is_valid(-300)) # False
print(Temperature.is_valid(25)) # TrueThe method has one parameter, celsius, and it is the only value the caller supplies. Nothing about the class or any instance is involved in the calculation. That is the sign of a good static method: the body would work unchanged if you moved it outside the class.
Calling a static method
You can call a static method on the class or on an instance. Both calls run the same function with the same result.
class Temperature:
@staticmethod
def is_valid(celsius):
return celsius >= -273.15
t = Temperature()
print(Temperature.is_valid(10)) # True
print(t.is_valid(10)) # True
print(type(Temperature.__dict__["is_valid"]).__name__) # staticmethodThe last line shows what the class actually stores. The class dictionary holds a staticmethod object that wraps your function. When you look the name up, through the class or an instance, that wrapper hands back the plain function. It does not insert self or cls.
Why not just use a module-level function?
A static method behaves like a module-level function, so you may wonder why you would put it in a class. The reasons are organizational:
- Grouping. The function is closely tied to the class's purpose, and keeping it in the class namespace makes the relationship visible.
Temperature.is_validtells the reader what is being validated. - Discoverability. Anyone who has the class can find its helpers with
dir()or an editor's autocomplete. - Name collisions. Many classes can each have an
is_validwithout clashing, because each lives in its own namespace.
If a helper is used by many unrelated classes, a module-level function is usually the better home. Python does not require static methods. Many codebases use them sparingly.
A helper used by other methods
Static methods are often private helpers for other methods in the same class. Inside an instance method, you reach the helper through self. Inside a class method, you reach it through cls. Either way you avoid hard-coding the class name.
class Temperature:
def __init__(self, celsius):
if not self.is_valid(celsius):
raise ValueError("below absolute zero")
self.celsius = celsius
@staticmethod
def is_valid(celsius):
return celsius >= -273.15
print(Temperature(20).celsius) # 20
try:
Temperature(-500)
except ValueError as error:
print(error) # below absolute zeroself.is_valid(celsius) passes one argument, and the function receives one argument. Because the method is static, self is not added to the call.
Static method versus instance method without the decorator
Leaving off @staticmethod changes how Python treats the function. A plain function in a class body becomes an instance method, and calling it on an instance passes the instance as the first argument.
class Temperature:
def is_valid(celsius): # missing @staticmethod
return celsius >= -273.15
print(Temperature.is_valid(10)) # True: works when called on the class
try:
Temperature().is_valid(10)
except TypeError as error:
print(error)The call on the class works because no binding happens there. The call on the instance fails with a TypeError. Python passes the instance plus 10, which makes two arguments for a function that accepts one. This is the most common static-method bug. It is easy to miss because the class-level call appears to work.
Static methods and inheritance
A static method has no cls, so it cannot know which class it was called on. Subclasses inherit it unchanged. A subclass can override it by defining a method with the same name, but the static method itself will never adapt to the subclass. If the method needs to create instances of the calling class, or read class attributes that subclasses may change, it should be a class method, which a later chapter compares in detail.
Summary of the receiving rules
| Kind | Decorator | First argument | Typical use |
|---|---|---|---|
| Instance method | none | `self`, the instance | Work with one object's data |
| Class method | `@classmethod` | `cls`, the class | Alternative constructors, class-level state |
| Static method | `@staticmethod` | none | Helpers grouped with a class |
Exercise
A class has this method written without a decorator: def double(n): return n * 2. Calling Math.double(4) returns 8, but calling Math().double(4) raises a TypeError. Why does this happen, and how do you fix it so both calls work?
Show answer
Without a decorator, double is an instance method. Called on the class there is no binding, so n is 4. Called on an instance, Python passes the instance as the first argument and 4 as the second, which gives two arguments for a one-parameter function. Fix it by adding @staticmethod above the def, so Python passes no automatic argument in either call.
Exercise
Write a class Palette with a static method is_hex_color(text) that returns True when text starts with "#" and has exactly 7 characters. Show one call on the class and one on an instance.
Show answer
class Palette: @staticmethod def ishexcolor(text): return text.startswith("#") and len(text) == 7 print(Palette.ishexcolor("#ff8800")) # True print(Palette().ishexcolor("ff8800")) # False