Can __iter__ be used as a classmethod?

Alex Martelli aleax at aleax.it
Tue Mar 4 13:36:35 CET 2003


Giovanni Bajo wrote:

> 
> "Lulu of the Lotus-Eaters" <mertz at gnosis.cx> ha scritto nel messaggio
> news:mailman.1046733846.16852.python-list at python.org...
>> "Bjorn Pettersen" <BPettersen at NAREX.com> wrote previously:
>> |I would like to be able to traverse the content of a class (not an
>> |instance) using a regular for loop: "for item in MyClass:...".
> 
>> If you want to add methods to a *class*, you create the class using a
>> custom metaclass:
> 
> So, what is classmethod exactly doing? Looking at the example snippet, it
> seems like it added a new method "items()" to the class.

It does -- it adds a (class) method to the class object. "Lulu"'s
assertion should pedantically be rephrased as: "if you want to add
SPECIAL methods that WILL AFFECT OPERATIONS ON a *class* [as opposed
to operations on *instances* of the class], you create the class
using a custom metaclass".

E.g., if X is a class, X.__iter__ affects iterations on INSTANCES
of X, *NOT* iterations on X itself; the latter are instead affected
by type(X).__iter__, if any.  type(X) is X's metaclass -- unless
it's a custom one, type(X) will be the built-in named 'type', which
has no special method __iter__.

This doesn't apply to "ciassic classes", which, for backwards
compatibility reasons, need to keep old, muddled semantics, and
can't really have custom metaclasses anyway (their metaclass is
types.ClassType, and it doesn't fit the new, regular model).

Attributes that you look up on a specific object are not the
same thing as special-methods that are looked up (on the TYPE
of the object -- except for classic classes) by operations
that you perform on the object.  Normal method calls use normal
attribute lookup.


Alex





More information about the Python-list mailing list