Đây là mã của tôi:Tại sao một đối tượng có thể lặp lại không phải là một trình lặp?
from collections import deque
class linehistory:
def __init__(self, lines, histlen=3):
self.lines = lines
self.history = deque(maxlen=histlen)
def __iter__(self):
for lineno, line in enumerate(self.lines,1):
self.history.append((lineno, line))
yield line
def clear(self):
self.history.clear()
f = open('somefile.txt')
lines = linehistory(f)
next(lines)
Lỗi:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'linehistory' object is not an iterator
Tôi không có ý tưởng tại sao các đối tượng linehistory
không phải là một iterator vì nó đã bao gồm __iter__
phương pháp trong the
lớp.
Bạn cũng cần phải xác định một 'tiếp theo() 'phương pháp (hoặc '__next __()' cho Python 3). – xyres
Thiếu phương thức '__next__': http://pymbook.readthedocs.org/en/latest/igd.html#iterators – schwobaseggl
Phương thức' __iter__' làm cho đối tượng của bạn trở thành [iterable] (https://docs.python.org/ 3.5/library/collections.abc.html # collections.abc.Iterable), trong khi phương thức '__next__' biến nó thành một [iterator] (https://docs.python.org/3.5/library/collections.abc.html# collections.abc.Iterator). Sử dụng 'lines = iter (linehistory (f))' và bạn sẽ ổn. – Vincent