[Tutor] static methods and class methods

Alan Gauld alan.gauld at btinternet.com
Fri Jun 13 01:48:54 CEST 2008


"Kent Johnson" <kent37 at tds.net> wrote>

>   I am still unsure of the difference of static and class methods.

You are not alone, it is confusing!

> A class method receives the class it was called on as the first
> argument. This can be useful with subclasses. A staticmethod doesn't
> get a a class or instance argument. It is just a way to put a plain
> function into the scope of a class.

And that's the definition of the difference in Python.
In the wider world of OOP they are two names for the same concept.
Smalltalk and Lisp etc used the term "class method" to mean a
method that applied to the class as a whole.

C++ introduced the term "static method" to reflect the fact that it
was loaded in the static area of memory(*) and thus could be called
wiothout instantiating an object. This meant it could effectively be
used as a class method.

[(*) In C it is possible to prefix a normal function definition with
the word static to get the compiler to load the fiunction into
static memory - this often gives a performance improvement.]

Python started off implementing "static methods" then later
developed the sligtly more powerfull and flexible "class methods" and
rather than lose backward compatibility called them classmethod.
So in Python we have two ways of doing more or less the same
(conceptual) thing.

> Both of these are rarely used; I don't think I have ever written a
> class method in live code. I have used staticmethods as a convenient
> way to put a function into a class namespace.

In contrast most of my major projects have used class methods
in some way or other. Often in conjunction with factory classes or
as factory methods, but also as a persistence mechanism, a
streaming mechanism or as a database access technique.
(In Python there are so many good ORMs that the latter use is
rarely necessary, but in other languages it can be an easy way
of instantiating objects stored in a database.)

They are also very powerful tools for writing OOP based MIS
systems where you tend to be collecting information at the class
level as well as the object level.

But I think they are a bit like metaclasses, if you are not used
to having them you tend to find other ways of doing the job.
They are rarely essential, just sometimes a convenient shortcut.
And class methods are often used in conjunction with
meta-classes

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list