Python @staticmethod vs @classmethod
July 2, 2008 § 6 Comments
Being educated under Java background, static method and class method are the same thing.
But not so in Python, there is subtle difference:
Say function a() is defined in Parent Class, while Sub Class extends Parent Class
If function a() has @staticmethod decorator, Sub.a() still refers to definition inside Parent Class. Whereas,
If function a() has @classmethod decorator, Sub.a() will points definition inside Sub Class.
Let’s talk about some definitions here:
@staticmethod function is nothing more than a function defined inside a class. It is callable without instantiating the class first. It’s definition is immutable via inheritance.
@classmethod function also callable without instantiating the class, but its definition follows Sub class, not Parent class, via inheritance. That’s because the first argument for @classmethod function must always be cls (class).
Reference:
Thanks for this. Very helpful.
[…] this for […]
Nice post on explaining @staticmethod and @classmethod.
However, the reference link you provided above can not be found.
Thanks for the helpful tip, always wondered what the difference was!
Great explanation!
Thanks. Im new to python and wasn’t sure what @staticmethod meant, but this laid it out for me.