Can __iter__ be used as a classmethod?

Phillip J. Eby pje at telecommunity.com
Thu Mar 13 21:13:18 CET 2003


mis6 at pitt.edu (Michele Simionato) wrote in message news:<2259b0e2.0303061331.2b0b2028 at posting.google.com>...
> 
> I was not familiar with staticmethods neither (I do not come from Java or
> C++), nevertheless I am disturbed by the confusion between "metamethods"
> (regular methods in the metaclass) and classmethods. If Samuele is
> right (I have no experience in Smalltalk) class methods in Smalltalk
> are actually metamethods. And this make much more sense to me than
> Python classmethods. This is a puristic point of view, of course,
> and I know that "practicality beats purity" ;)

There is actually an important difference between static, metamethods,
and class methods here.  Important to *me*, anyway...

Class methods (like Java "static" methods) can be overridden in a
subclass, directly.  Metaclass methods require subclassing the
metaclass to override.  This is important when I wish to have a
*class* implement a particular behavior, and it must delegate portions
of the behavior to other *class* methods.  E.g.:

class Number(object):

    def fromXML(klass, node):
         return klass.fromString(node.text)

    fromXML = classmethod(fromXML)

    def fromString(klass, s):
         return klass(int(s))

    fromString = classmethod(fromString)

Now, if in a subclass I redefine 'fromString', then the 'fromXML'
method will still work correctly.  If I do this with metaclass
methods, I must subclass the metaclass for every subclass where I wish
to override a class method.

I use *both* metaclass methods *and* class methods in my software, but
I use them for different things.  Class methods are for when the
behavior will vary by class, and metaclass methods are for when the
behavior will vary by metaclass.

Personally, I have never bothered to use a staticmethod, as I have
never seen the point of using one.  Sooner or later, I would find I
needed to refer to the class, so I prefer to just start out with
classmethod instead of having to change it later.  __new__ is the only
staticmethod I've ever bothered with, and I'm not actually sure why
it's not a classmethod!


> I also was confused by the *syntactic* similarity between staticmethods
> and classmethods: at the beginning I was induced to think that they
> were similar concepts, but actually they are completely different
> beasts. I mantain that the introduction of classmethods make harder 
> the life for newbies without giving a definitive advantage, whereas
> on the contrary I would welcome a ternary operator.

I think it would be better to say that staticmethod is the one that
doesn't give any functionality.  I also think staticmethod is poorly
named, since it does not produce a method, and it definitely doesn't
do what a 'static method' does in Java or any other language I know
of.




More information about the Python-list mailing list