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

Tim Chase python.list at tim.thechases.com
Tue Aug 9 20:29:30 EDT 2011


On 08/09/2011 07:11 PM, Terry Reedy wrote:
> On 8/9/2011 5:43 PM, 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
>
> And what are the items in a class that you expect that to produce?

I can see doing something like

   class MyClass:
     instances = []
     def __init__(self, *args, **kwargs):
       self.instances.append(self)
       # ...

   a = MyClass(...)
   b = MyClass(...)
   for instance in MyClass:
     do_something(instance)

I was curious/surprised to find that

   class MyClass:
     instances = []
     @classmethod
     def __iter__(cls):
       for i in cls.instances:
         yield i
     def __init__(self):
       self.instances.append(self)

didn't work as I expected since MyClass then has an __iter__ 
property that should know about the class.

-tkc






More information about the Python-list mailing list