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
Temperature.to_fahrenheit(100)is called on the class itself. NoTemperatureobject is created.- Inside
describe, the same static method is called asself.to_fahrenheit(...). Both ways work. from_fahrenheitgets the class asclsand callscls(...)to build a new object. This is the usual job of a class method: a second way to create objects. Because it usesclsand notTemperature, a child class that inherits it would create objects of the child class.round(body.celsius, 1)keeps the output short. Float results often have long decimals:Temperature.from_fahrenheit(100).celsiusis37.77777777777778.
Which one to use
| Method type | First parameter | Use it when the method needs |
|---|---|---|
| normal | self | the data of one object |
@classmethod | cls | the class, for example to create objects |
@staticmethod | none | neither: it is a helper |
If a static method is not closely tied to the class, a normal function in the module is often simpler.