Class vs static methods in Python

In this article I'll try to explain what are staticmethod and classmethod, and what the difference is between them. staticmethod and classmethod both use decorators for defining a method as a staticmethod or classmethod. Please take a look at the article Python Decorators Overview for a basic understanding of how decorators works in Python.

Simple, static and class methods

The most used methods in classes are instance methods, i.e instance is passed as the first argument to the method.

For example, a basic instance method would be as follows:

This gives us the following output:

Python Instance Method Example

After looking at the code sample and diagram:

  • In 1 and 2, the arguments are passed to the method.
  • On 3, the self argument refers to the instance.
  • At 4, we do not need to provide the instance to the method, as it is handled by the interpretor itself.

Now what if the method we want to write interacts with classes only and not instances? We can code a simple function out of the class to do so but that will spread the code related to class, to out of the class. This can cause a future code maintenance problem, as follows:

Gives us the following output:

The Python @classmethod

What we want to do now is create a function in a class, which gets the class object to work on instead of the instance. If we want to get the no of instances, all we have to do is something like below:

 

Using features introduced after Python 2.2, we can create a method in a class, using @classmethod.

We get the following output:

The benefit of this is: whether we call the method from the instance or the class, it passes the class as first argument.

The Python @staticmethod

Often there is some functionality that relates to the class, but does not need the class or any instance(s) to do some work. Perhaps something like setting environmental variables, changing an attribute in another class, etc. In these situation we can also use a function, however doing so also spreads the interrelated code which can cause maintenance issues later.

This is a sample case:

Which gives us the following output:

Here if we use a @staticmethod, we can place all code in the relevant place.

Which gives us the following output:

Here is a more comprehensive code example, with a diagram to show you

How @staticmethod and @classmethod are different.

Here's a diagram to explain what's going on:

Comparison of @staticmethod vs @classmethod

About The Author