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

Terry Reedy tjreedy at udel.edu
Tue Aug 9 20:42:41 EDT 2011


On 8/9/2011 8:29 PM, Tim Chase wrote:
> 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:

for instance in MyClass.instances:

> 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.

I strongly suspect that iter(ob) starts the lookup for __iter__ with 
type(ob). I would also expect
   for instance in MyClass.__iter__()
to work, but that is a waste since instances is already iterable.

-- 
Terry Jan Reedy




More information about the Python-list mailing list