The Art of Tech

 

Python @staticmethod and @classmethod

 

(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/

Friday, December 3, 2010

 
 
Made on a Mac

next >

< previous