Class and static methods
Python also provides @classmethod
and @staticmethod
decorators for use inside classes.
I have covered @classmethod
in Module 3, so I won’t discuss this again in too much detail.
I would just like to briefly compare the differences between instance methods, class methods and static methods in Python.
Note to C++/Java users: a class method in Python is actually equivalent to a static method in C++/Java (and most other languages). A static method in Python is a completely different thing! Pure confusion! 😵
Examine the code below, and compare the differences between the three types of methods. Then run it, and examine the output. How are they different?
class ExampleClass:
def instance_method(self):
print("instance method called", self)
@classmethod
def class_method(cls):
print("class method called", cls)
@staticmethod
def static_method():
print("static method called")
e = ExampleClass()
e.instance_method()
e.class_method()
e.static_method()
You can also invoke both class methods and static methods using the class name ExampleClass
. But you must invoke instance methods with an instance of ExampleClass
.
ExampleClass.instance_method()
## TypeError: instance_method() missing 1 required positional argument: 'self'
ExampleClass.class_method()
## class method called <class '__main__.ExampleClass'>
ExampleClass.static_method()
## static method called
You will have noticed that:
self
ininstance_method()
is an instance ofExampleClass
cls
inclass_method()
isExampleClass
- and
static_method()
does not require either of these!
The @classmethod
decorator forces the first argument of the method to be an ExampleClass
.
The @staticmethod
decorator will turn the method into a normal function (but only accessible inside the scope of ExampleClass
). So static methods in Python have access to neither instance nor class properties of the Class. It is mainly used to group relevant utility functions inside the class.
I personally do not recommend using @staticmethod
, as I find that it does not really fit in well with Object-Oriented Design. The use cases that I found for static methods can easily be done without a static method (and in fact, might even be better without). It would be better, for example, to place any utility functions as methods in a separate class. This is called the Single Responsibility Principle. It is enough that you know @staticmethod
exists!