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

Gelonida N gelonida at gmail.com
Tue Aug 9 23:43:01 CEST 2011


Hi,

I am just curious. There  is no real use case:

If I have a class and I want that its instances are iterable I can just
add a class metohod named __iter__()


example:

class MyClass(object):
	def __iter__(self):
		for val in range(10):
			yield val


this allows me to do:
myobj = MyClass()
for val in myobj:
	print val


Now I wondered whether there is any way to  implement a class such, that
I can write


for val in MyClass:
	print val

I know I can implement  a classmethod (e.g myclassmethod() ) and write:

for val in MyClass.myclassmethod():
	print val

but I wondered whether classed can be made iterable

Thanks in advance for your answers.




More information about the Python-list mailing list