Most methods in a class take self and work on one object. A static method takes nothing and is really just a function that happens to sit in the class.

Use one for a calculation that needs the class for organisation only, and not for the data.

Why Use Static Methods?

Use one for a calculation that needs the class for organisation only, not for the data.

Calling it the normal way means making an object first:

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

obj = Spaceship()
obj.start()

Here, the self keyword within the start method refers to the object instance. If you dared to call the method directly without an instance (like Spaceship.start()), Python wouldn’t be too happy about it and would throw an error.

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

Spaceship.start()

The reason? You haven’t instantiated an object. In OOP, instantiation is typically a prerequisite.

➜  ~ 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'

Using Static Methods: A Practical Scenario

Imagine you’re building functionality related to a class, but without the need for specific object instances. Take unit conversion functions, such as converting kilometers to miles. To which object should such functions belong?

Here’s where static methods come in handy. They’re crafted for scenarios where you want methods associated with a class but without a dependency on object instances.

Put the @staticmethod decorator on top. It tells Python the method does not need an instance.

class MyClass:
@staticmethod
def myMethod():
pass

After that you call it on the class, with no object:

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

Spaceship.start()

Upon execution, the above code yields:

➜  ~ python3 example.py
start

Static methods don’t have access to instance-specific data or methods. This might seem a bit off-kilter, especially when thinking from an OOP perspective. But, in reality, they serve a purpose. While regular class methods are the bedrock of most software systems, static methods often find their calling as utility or helper methods, offering standalone functionalities.

It’s essential to discern when to use which and understand the role each method type plays in crafting effective Python programs.

If you want to try this yourself, the exercises on PyChallenge turn the same idea into a few short problems with instant feedback.