Python @staticmethod and @classmethod

Categories: Python
Tags:
Comments: No Comments
Published on: December 10, 2010

(Lifted from Didip Kerabat’s blog HERE)

Unlike Java, where static method and class method are the same thing, 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:

http://rapd.wordpress.com/2008/07/02/python-staticmethod-vs-classmethod/

Post to Twitter

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Welcome , today is Wednesday, May 31, 2023