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

G

Gelonida N

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

Steven D'Aprano

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.

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top