[Python-talk] Notes from PySIG, 28-Feb-2009
Kent Johnson
kent37 at tds.net
Fri Feb 29 22:38:40 EST 2008
Lloyd Kvam wrote:
> Kent pointed out that
> for record in Myclass.__iter__():
> will work and also provided a simple metaclass workaround.
>
> On reflection, I think that the notion of making __iter__ a classmethod
> is a mistake.
I tend to agree that this is a bad idea, but it is possible. Here is a
short demo of defining an __iter__() method in a metaclass so that
direct iteration of the class object is possible. In this cas the
construction of the actual iterator is delegated back to the class:
class MyClass(object):
class __metaclass__(type):
def __iter__(self):
return MyClass._iter()
@classmethod
def _iter(cls):
for i in range(4):
yield i
for i in MyClass:
print i
Kent
More information about the Python-talk
mailing list