我正在尝试创建一个可迭代的类,但可以这么说,我一直在把头撞到墙上,得到“对象不可迭代”。这是我的代码:
class myiterable:
def __init__(self, somelist):
self.i = 0
self.l = somelist
def __iter__(self):
return self
def __next__(self):
if self.i < len(self.l):
self.i = self.i + 1
return self.l[self.i-1]
else:
raise StopIteration
for i in myiterable([1, 2, 3, 4, 5]):
print(i)
怎么了?我也试过next(self)
代替__next__(self)
无济于事!