@staticmethod, and choosing the right kind
🌍 In real life. A shop keeps a calculator on the counter. The calculator doesn't need to know which customer is paying or even which shop it's in: 2 + 2 is 4 everywhere. It's kept there simply because that's where it's useful.
A static method is that calculator: a plain function kept inside a class because it belongs with it. It gets neither self nor cls, just its own arguments.
The idea in one sentence: a @staticmethod is a plain function kept inside a class because it belongs there; it gets neither self nor cls.
Its words:
@staticmethod: marks a method with no automatic first argument- helper: a small function related to the class, like working out a price
- choosing: needs the object → normal method; needs the class → class method; needs neither → static method
class Shop:
def __init__(self, name):
self.name = name
@staticmethod
def add_vat(price):
return round(price * 1.15, 2)
print(Shop.add_vat(100)) # call it on the class...
print(Shop("Corner").add_vat(20)) # ...or on an objectWhich kind should a method be? Ask what it needs:
- it needs this object's data (
self.balance) → a normal method - it needs the class (to make objects, or a class-wide counter) →
@classmethod - it needs neither →
@staticmethod
A pizza shop shows all three: each pizza describes itself, the shop has a ready-made margherita recipe, and working out a price from the number of toppings is pure arithmetic.
class Pizza:
def __init__(self, name, toppings):
self.name = name
self.toppings = toppings
def describe(self): # needs this pizza
return self.name + " with " + ", ".join(self.toppings)
@classmethod
def margherita(cls): # needs the class
return cls("Margherita", ["tomato", "mozzarella"])
@staticmethod
def price_for(n): # needs neither
return 300 + 50 * n
p = Pizza.margherita()
print(p.describe())
print(Pizza.price_for(len(p.toppings)), "taka")Why keep it in the class? The function is found where a reader expects it (Pizza.price_for(size)), it's grouped with the code it helps, and it can be called on the class or on any object.
Mistakes and edge cases.
- Adding self anyway.
def price_for(self, size):under@staticmethodmakesselfan ordinary parameter, so the call is one argument short. - Needing the object after all. If the helper starts reading
self.size, it should be a normal method. - A static method for everything. If a function has nothing to do with the class, a plain function outside it is clearer.
Quiz
What does this print?
class MathTools: @staticmethod def square(n): return n * n print(MathTools.square(6))What does a static method get as its first parameter?
- Only the arguments you pass: no self and no cls
- self
- cls
A method
is_overdrawn()checks whetherself.balance < 0. Which kind should it be?- A normal method: it needs this object's balance
- @staticmethod
- @classmethod
A method
from_json(text)reads some text and makes a new object. Which kind fits best?- @classmethod: it uses cls(...) to make the object
- @staticmethod
- A normal method
What does this print?
class Grade: @staticmethod def letter(score): if score >= 80: return "A" return "B" print(Grade.letter(85) + Grade.letter(70))Which line makes the call price_for("L") fail?
class Pizza: @staticmethod def price_for(self, size): return {"S": 300, "L": 600}[size] print(Pizza.price_for("L"))
Coding tasks
Write a class
MathToolswith a static methodis_even(n)that returns True when n is even.Write a class
Converterwith a static methodkm_to_miles(km)that returns km × 0.621371, rounded to 2 decimal places.Pizzais started for you. Add a class methodmargherita()that returnsPizza("Margherita", ["tomato", "mozzarella"]), and a static methodprice_for(n)that returns 300 + 50 × n.