PythonMastery

Static method in Python

A static method is a function kept inside a class that needs no object. Compare @staticmethod, @classmethod and a normal method in one class.

A static method is a plain function that lives inside a class. It does not get self or the class, so it cannot read or change any object. Use one when a helper belongs with the class but does not need its data.

The program

python
class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius

    # normal method: needs an object (self)
    def describe(self):
        return f"{self.celsius} °C is {self.to_fahrenheit(self.celsius)} °F"

    # static method: no self, no cls
    @staticmethod
    def to_fahrenheit(celsius):
        return celsius * 9 / 5 + 32

    # class method: gets the class, often used as another way to create objects
    @classmethod
    def from_fahrenheit(cls, fahrenheit):
        return cls((fahrenheit - 32) * 5 / 9)


print(Temperature.to_fahrenheit(100))
print(Temperature(25).describe())

body = Temperature.from_fahrenheit(98.6)
print(round(body.celsius, 1))
output
212.0
25 °C is 77.0 °F
37.0

How it works

Which one to use

Method typeFirst parameterUse it when the method needs
normalselfthe data of one object
@classmethodclsthe class, for example to create objects
@staticmethodnoneneither: it is a helper

If a static method is not closely tied to the class, a normal function in the module is often simpler.

Learn the idea: Object-Oriented Programming, Decorators: Functions That Wrap Functions