Static methods do not require object creation from a class to be called, they can be called directed on the class.

A static method can always be called, but is part of a class. This is different from a regular class method, that needs object initiation and is called on the object.

Normally calling a class method requires you to create an object and call the method: Not the case with static methods.

Related course: Python Programming Courses & Exercises

Introduction

In object orientated programming, a method is called on an object but defined in a class. You can not call the method defined in the class directly.

A non static method needs an object to be initialized:

class Spaceship(object):
def start(self):
print('start')

obj = Spaceship()
obj.start()

The self keyword in the start method refers to the object. Because static methods can be called without object creation, they do not have a self keyword.

If you try to call the method directly, Spaceship.start() it throws an error.

class Spaceship(object):
def start(self):
print('start')

Spaceship.start()

Because an object is not created, an error is thrown. In normal object orientated programming, an object must be created from a class first.

➜  ~ python3 example.py
Traceback (most recent call last):
File "example.py", line 6, in <module>
Spaceship.start()
TypeError: start() missing 1 required positional argument: 'self'

Static method example

Sometimes there is functionality that is related to a class, but does not need any objects. What object do unit conversion functions (kilmometer to miles) belong to?
In such situation, you may want to create a static method.

Create a class and add a method. You should explicitly define it’s a static method by adding the decorator @staticmethod.

In other words: To make a method a static method, add the decorator @staticmethod.

The format is then:

class MyClass:
@staticmethod
def myMethod():
pass

Once you defined the class, you can call the methods directly.

class Spaceship:

@staticmethod
def start():
print('start')

Spaceship.start()

If you run the program it will show this output:

➜  ~ python3 example.py
start

This calls the method start() without creating an object. Unlike normal class methods, they do not have access to objects variables.

This may be odd, as it seems counter to the concept of object orientated programming.

In most of the computer software you’ll find regular class methods. Static methods are usually used as helpers.

If you are a Python beginner, then I highly recommend this book.

Download exercises