Can __iter__ be used as a classmethod?

Alex Martelli aleax at aleax.it
Tue Mar 4 16:08:16 EST 2003


Giovanni Bajo wrote:

> 
> "Michele Simionato" <mis6 at pitt.edu> ha scritto nel messaggio
> news:2259b0e2.0303041023.43e8b81f at posting.google.com...
> 
>> It seems to me I could always use a regular method instead of
>> a classmethod, by accessing the class trough self.__class__ or
>> type(self), therefore classmethods only provide a very small amount
>> of syntactical sugar.
> 
> Actually, they let you also call the method without any instance of the
> class (they do not need to be bound to any instance).

Yes, that's difference #1.


>> Actually they seems to me an unessential complication to the language,
>> expecially because they are easily confused with the methods in the
>> metaclass.
        ...
> The only difference I can see is:
> 
>>>> a = A()
>>>> a.g()
> Hello from <class '__main__.A'> , value is 10
>>>> a.f()
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
> AttributeError: 'A' object has no attribute 'f'
> 
> This is because of the lack of transitivity in the 'inheritance' from
> types, as explained by Alex in another post in this thread.

And that's difference #2.


> So, what are the other differences (if any)? Why do classmethods exist?

Aren't these reasons enough?  How else would you code a method that
you can indifferently call either on any instance or on the class
object itself?  And _having_ to write a custom metaclass as the
only way to get classmethods would be somewhat of an overkill.

Whether static methods (which to many are familiar from C++ or Java)
and class methods (which have some pluses and some minuses, and to 
some are familiar from Smalltalk) need to exist at all is moot -- C++'ers
and Javaites have been clamoring for them for a long time, not wanting
to use free-standing (module top-level) functions instead (and in
effect, a free-standing function could not be written to receive the
classobject automatically -- and custom metaclasses where a nightmare
before Python 2.2).

Overall I'm slightly happier to have them in Python than not, but I
do realize they contribute to "featuritis" -- Python does keep getting
richer with every release, as it's always easier to give in to the
pressure of those who DO want the feature (and can muster good direct
arguments and use-cases for it), when the only negative is "the more
feechurs we keep piling up, the less simple our beloved language".  Sigh.


Alex





More information about the Python-list mailing list