你好我正在嘗試建立一個基于這樣的班級串列
class DummyList(Iterator):
...
def __next__(self) -> int:
list = [1, 2, 3, 4, 5]
for i in list:
yield i
我正在這樣使用
dl = DummyList()
for i in dl:
print(i)
我期望的輸出是
1
2
3
4
5
但相反我得到
12345
12345
12345
....
我該如何解決這個問題?
謝謝
uj5u.com熱心網友回復:
這將是實作迭代器的正確方法:
from collections.abc import Iterator
class DummyList(Iterator):
def __init__(self):
self.lst = [1, 2, 3, 4, 5]
self.current = -1
def __iter__(self):
return self
def __next__(self):
self.current = 1
if self.current < len(self.lst):
return self.lst[self.current]
raise StopIteration
這是輸出:
dl = DummyList()
for i in dl:
print(i)
1
2
3
4
5
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/521240.html
標籤:Python
下一篇:熊貓從鏈接域中提取單詞
