[Tutor] classmethod, staticmethod functions (decorator related)

Alan Gauld alan.gauld at btinternet.com
Mon Sep 13 19:11:13 CEST 2010

"Huy Ton That" <huyslogic at gmail.com> wrote

> I was taking a look at the module decimal.py as you cited, and it 
> makes
> sense now. Looks very useful to make tools without having to 
> instantiate
> anything.

Thats not a good way to think of them.
Doing things without instantiating is usually better done by a 

Class methods are for doing things to the class.
eg you might use one to get a count of all the instances - or even a 
Or you might want to reset the status of a group of instances. Or find
a particular instance out of all existing ones, and if its not there
create a new instance and return it.

Class methhods are often commonly used for providing persistence
mechanisms with databases or marshalling pools for network programming
etc etc.

>> The most common use for classmethods is to implement alternative
>> constructors. For example, in the Decimal class starting in version 
>> 2.7
>> and 3.1, you have two constructors:

Whilst I'd question if its *the most common* it is certainly another 
use for them in Python which doesn't offer multiple constructors as
standard. This is rather like the factory methods of Objective C.

I've rarely worked on any significant OOP project that did not use
class methods somewhere in its design. But they tend not to be used
in the typical small-scale code used in tutorials, so it's hard for a 
to really get a feel for how they are used and why.

Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list