When should use @classmethod in python
1 min readMar 28, 2021
What is @classmethod
According to the python document, @classmethod is defined like the below.
A class method can be called either on the class (such as C.f()) or on an instance (such as C().f()).
@classmethod is different with @staticmethod.
Class methods are different than C++ or Java static methods. If you want those, see staticmethod().
When should use @classmethod
There is not right answer presumably.
Google Python Style Guide explains one of the cases is like the below.
Use classmethod only when writing a named constructor or a class-specific routine that modifies necessary global state such as a process-wide cache.
One of the answers in StackOverflow explains like the below.
If your method needs access to an instance, make it a regular method. If it needs access to the class, make it a classmethod. If it doesn't need access to the class or the instance, make it a function.
Reference
- https://stackoverflow.com/questions/10586787/when-should-i-use-classmethod-and-when-def-methodself#:~:text=Basically%2C%20you%20should%20use%20a,instantiated%20and%20need%20less%20memory.
- https://stackoverflow.com/questions/11788195/module-function-vs-staticmethod-vs-classmethod-vs-no-decorators-which-idiom-is