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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…