15.5. Static Methods

A static method doesn’t have a self or cls parameter. Static methods are effec- tively just functions, because they can’t access the attributes or methods of the class or its objects. Rarely, if ever, do you need to use static methods in Python. If you do decide to use one, you should strongly consider just creat- ing a regular function instead.

We define static methods by placing the @staticmethod decorator before their def statements. Here is an example of a static method.

>>> class ExampleClassWithStaticMethod:
>>>     @staticmethod
>>>     def sayHello():
>>>         print('Hello!')
>>> # Note that no object is created, the class name precedes sayHello():
>>> ExampleClassWithStaticMethod.sayHello()
Hello!

There would be almost no difference between the sayHello() static method in the ExampleClassWithStaticMethod class and a sayHello() function. In fact, you might prefer to use a function, because you can call it without having to enter the class name beforehand.

Static methods are more common in other languages that don’t have Python’s flexible language features. Python’s inclusion of static methods imitates the features of other languages but doesn’t offer much practical value.