Python 3D Academyবাংলা

@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 object
add_vat never touches self or cls: it only uses price.

Which 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 @staticmethod makes self an 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

  1. What does this print?

    class MathTools:
        @staticmethod
        def square(n):
            return n * n
    
    print(MathTools.square(6))
  2. What does a static method get as its first parameter?

    • Only the arguments you pass: no self and no cls
    • self
    • cls
  3. A method is_overdrawn() checks whether self.balance < 0. Which kind should it be?

    • A normal method: it needs this object's balance
    • @staticmethod
    • @classmethod
  4. 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
  5. What does this print?

    class Grade:
        @staticmethod
        def letter(score):
            if score >= 80:
                return "A"
            return "B"
    
    print(Grade.letter(85) + Grade.letter(70))
  6. 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

  1. Write a class MathTools with a static method is_even(n) that returns True when n is even.

  2. Write a class Converter with a static method km_to_miles(km) that returns km × 0.621371, rounded to 2 decimal places.

  3. Pizza is started for you. Add a class method margherita() that returns Pizza("Margherita", ["tomato", "mozzarella"]), and a static method price_for(n) that returns 300 + 50 × n.