[Tutor] Declaration order of classes... why it is important?

Alan Gauld alan.gauld at btinternet.com
Fri Aug 28 19:03:39 CEST 2009


"Mac Ryan" <quasipedia at gmail.com> wrote

> I am not sure I understood the difference between staticmethod end
> classmethod, though, even if I can guess it has to do with subclassing,

I think it is mainly historical. staticmethod came first (I think)  and 
classmethod
was an improvement a couple of versions later. I think classmethod is the
preferred choice nowadays.

> Also, what is the advantage of using a method at class level rather than
> using it at object instance

There are two common cases:

1) You want to do something at the class level rather than instance
level - such as find all instances, or keep a count of all instances.
Or you may have a method or variable that affects all instances
simultaneously - perhaps activates or disables all network connections
say.

2) You want somethig that can be done without creating an instance,
or at least does not depend on whether any instances exist yet. This
is very common in Java which doesn't support standalone functions
but is not needed so much in Python because a module function is
usually a better option.

You can also use it to provide meta-class programming features
and other tricks, but frankly thats usually being too clever for your
own good! :-)

HTH,

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




More information about the Tutor mailing list