When should use @classmethod in python

cocoamaemae
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

--

--