Can __iter__ be used as a classmethod?

Lulu of the Lotus-Eaters mertz at
Tue Mar 4 00:17:43 CET 2003

"Bjorn Pettersen" <BPettersen at> 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:

    % cat
    from __future__ import generators
    class ClassIter(object):
        vals = ['a', 'b', 'c']
        class __metaclass__(type):
            def __iter__(cls):
                print 'iter'
                return cls.items()
        def items(cls):
            print 'items'
            for item in cls.vals:
                yield item
        items = classmethod(items)

    for x in ClassIter:
        print x

    % python

Yours, Lulu...

mertz@  | The specter of free information is haunting the `Net!  All the
gnosis  | powers of IP- and crypto-tyranny have entered into an unholy
.cx     | alliance...ideas have nothing to lose but their chains.  Unite
        | against "intellectual property" and anti-privacy regimes!

More information about the Python-list mailing list