This might be obvious for many, but based on my personal experience, I realized that people (including me) sometimes get confused on when to use @classmethod
and @staticmethod
. Hopefully this article will help clarify the usage of both.
Class method
First of all, what’s the definition of a class method? Based on Python’s official doc: “a class method receives the class as implicit first argument, just like an instance method receives the instance”. To declare a class method, we can use @classmethod
decorator:
A class method can be called either on the class (Example.foo()
) or on the instance level (Example().foo()
). The instance is ignored except for its class. Class method passes the derived class as the first implicit argument.
Static method
According to Python’s official doc, unlike class method, a static method does not receive an implicit first argument. To declare a static method, we can use @staticmethod
decorator:
Similar to class method, a static method can be called either on the class ( Example.bar()
) or on an instance (Example().bar()
).
When to use Class method and Static method
Based on the above definitions, class method and static method are arguably similar. So why do we need both, and what are their use cases? Let look at the following examples:
Example 1
The output from calling Example.foo('FOO')
and Example.bar('BAR')
are:
Message sent from foo: FOO
Message sent from bar: BAR
In this example, the effect of using class method and static method is similar and both ways are capable of doing this task.
Example 2
I this example, foo
is calling static methodbar
from the inside this body function. The output from calling Example.foo("FOO")
i:
Message sent from foo: FOO
attr_1
Message sent from bar: (from foo) BAR
As we can see from the output, class method is capable of accessing attributes and methods which are in the scope of class level (not instance level). However, this is not the case for static method since static method cannot have access to other class methods or class attributes (we are not passing class as the first implicit argument).
In addition, both class method and static method do not have access to instance level’s attributes and methods.
Therefore, when design a method, if the method requires access to any of class level’s attributes or methods, class method is a suitable candidate, otherwise, static method is already sufficient.