[Tutor] Staticmethod & Classmethod Question

Alan Gauld alan.gauld at btinternet.com
Sat Feb 25 10:32:23 CET 2012


On 25/02/12 08:31, Chris Kavanagh wrote:

> I don't think, in my very short Python career, I've heard of a
> staticmethod or classmethod. There's very little explanation of them in
> the book. I've googled them, but am still confused on exactly what they
> are & why they should be used. The only sense I can make of them is, a
> staticmethod can be called WITHOUT actually creating an object first.

In general you can ignore staticmethod, it was an earlier attempt
to do what classmethod does. I suspect it is only kept around
because removing it would break some older code. (There are some
subtle differences in the way they work but they are not
significant IMHO). In most cases I would recommend using
classmethod nowadays.

Here is a link that summarises the diofferences succintly:
http://rapd.wordpress.com/2008/07/02/python-staticmethod-vs-classmethod/

So what do they do? What are they used for?

They define a method as belonging to the class itself rather than to 
instances of the class. This is best described by examples.
Consider a class of employees. You would create instance methods
to add, delete, modify, print an employee. but you could create class 
methods to, for example, find an employee out of all of the instances 
that exist. Or to return the total number of employees in existence. 
These two operations operate on the whole class of employees not on any 
single instance.

Some languages treat instance creation as a class method too, you ask 
the class to create a new instance of itself. Smalltalk is a good 
example of this. In Python we don't need to do that explicitly.

Because they operate on the class rather than on an instance they can be 
called without any instances being in existence. In the examples above 
the results would be empty/zero but the method could still be called.

HTH,

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list