Can __iter__ be used as a classmethod?

Alex Martelli aleax at aleax.it
Tue Mar 4 05:47:37 EST 2003


Bjorn Pettersen wrote:

>> From: Lulu of the Lotus-Eaters [mailto:mertz at gnosis.cx]
>> 
>> "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:
> 
> Thank you very much! Could you also explain why <wink>? (e.g. why can I
> make items() a classmethod but not __iter__, and how does
> __metaclass__.__iter__ get called from iter(ClassIter)? -- it doesn't
> show up when using dir()...)

In Python 2.2 and later (excepting, for backwards compatibility,
'classic classes') an operation always looks up the special methods
of interest on the CLASS (aka type) of the object being operated on.

The class of a class object is also conventionally known as its
"metaclass".  But the relationship of a class to its metaclass is
absolutely identical to that of any other instance to its class
(again excepting the muddied semantics of "classic classes" and
their instances, which need to stay around for backwards compat).

So, iter(x)  ALWAYS  attempts calling  type(x).__iter__(x), for
ANY x (excluding classic-class instances).

OTOH, explicitly accessing an attribute (including a callable
attribute -- a method) on any object x generally gets the attribute
on the object x itself (unless descriptors -- such as properties --
or fancy __getattribute__ overrides in type(x) dictate otherwise).

If you just forget the existence of "classic classes", everything
else is perfectly regular and predictable -- working with a class
and a custom metaclass is no different than working with any
other instance and that instance's type (aka class).


Alex





More information about the Python-list mailing list