On 08/08/17 02:22, boB Stepp wrote:

> "@staticmethod" then there are two ways of calling the method, using
> objects or using the class.  Is there some reason not to use the
> "ClassName.a_static_method()" syntax?  Are there intended uses for
> doing this?

classes are objects too...

You could have a list of objects, some of which are classes
and some instances.

Its nice to use polymorphism and just call the staticmethod (or
classmethod) and let the interpreter do the hard work without
having to test types - a nasty non-OO style of programming that
should be avoided if possible

> Class methods look to be something I will find difficult to find a use for.

Once you start using objects a lot they come in very useful.
I don't think I've built any significant OO system without
using at least a few class methods. Remember that class methods
conceptually act on the class as a whole - ie on all instances
both current and future. So any time you have a large group
of objects and you want to set some kind of state for all
of them you can use classmethods to set class state. Instance
methods can refer to the class state and modify their behaviour
accordingly. (Some OO gurus argue that you should only set
class state via a class method, although you can do it via an
instance too - but what if you need to set it when no
instances exist. In Python direct access allows that
from outside the class, but in other OO systems you need
a class method.)

Class methods are also the best place to put alternate
constructors - eg loading from a database given an
instance ID or by parsing a string representation.

Class methods can also be used to manage caches of instances,
do global searches of instances (eg from a database) etc.

>> (1) There are very, very few good uses for static methods in Python. If
>> you think you need a static method, you probably could just use a
>> regular module-level function.

Amen to that, I try to avoid staticmethods... and so far
have never found a valid use for one. I treat them as a
piece of legacy from earlier versions, prior to classmethods.

Alan G
Author of the Learn to Program web site
Follow my photo-blog on Flickr at:

Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:

Reply via email to