What makes something iterable in python

后端 未结 4 759
既然无缘
既然无缘 2020-12-02 11:01

What makes something iterable in Python? ie. can loop over it with for

Is it possible for me to create an iterable class in Python? If so, how?

4条回答
  •  广开言路
    2020-12-02 11:37

    To make a class iterable, write an __iter__() method that returns an iterator:

    class MyList(object):
        def __init__(self):
            self.list = [42, 3.1415, "Hello World!"]
        def __iter__(self):
            return iter(self.list)
    
    m = MyList()
    for x in m:
        print(x)
    

    prints

    42
    3.1415
    Hello World!
    

    The example uses a list iterator, but you could also write your own iterator by either making __iter__() a generator or by returning an instance of an iterator class that defines a __next__() method.

提交回复
热议问题