just for fun: make a class (not its instances) iterable

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Aug 9 19:54:25 EDT 2011


Gelonida N wrote:


> Now I wondered whether there is any way to  implement a class such, that
> I can write
> 
> 
> for val in MyClass:
> print val


One way to make an object iterable (there are others) is to add an __iter__
method to the object's class.

Unlike in some languages, classes in Python are themselves objects, which
means that classes themselves have a class, "type". The class of a class is
called the metaclass. So to make the class object (the instance) iterable,
use a metaclass.


>>> class MetaIter(type):
...     def __iter__(self):
...             for name in 'abcd':
...                     yield getattr(self, name)
...
>>> class MyClass(object):
...     __metaclass__ = MetaIter
...     # In Python 3, write as class MyClass(object, metaclass=MetaIter)
...     a, b, c, d, = 42, 23, -99, "Surprise!"
...
>>>
>>> for obj in MyClass:
...     print obj
...
42
23
-99
Surprise!




-- 
Steven




More information about the Python-list mailing list