【发布时间】:2019-04-07 16:31:23
【问题描述】:
我想在 Python 中创建一个行为类似于列表但可以循环迭代的类 用例示例:
myc = SimpleCircle()
print(len(myc))
j = iter(myc)
for i in range (0, 5):
print(next(j))
它将打印 一种 b C d 一个
到目前为止我尝试的代码是下面的代码
我知道问题出在我的__next__
方法 顺便说一句,这似乎被忽略了,即使我没有实现它,我也可以使用下一个
class SimpleCircle:
def __init__(self):
self._circle = ['a', 'b', 'c', 'd']
self._l = iter(self._circle)
def __len__(self):
return len(self._circle)
def __iter__(self):
return (elem for elem in self._circle)
def __next__(self):
try:
elem = next(self._l)
idx = self._circle.index(elem)
if idx < len(self._circle):
return elem
else:
return self._circle[0]
except StopIteration:
pass
【问题讨论】:
-
您是否尝试实现
itertools.cycle?
标签: python iterator next circular-list