【发布时间】:2020-12-01 17:06:30
【问题描述】:
我需要创建可以多次使用的生成器。我有这样的课程:
class iter_maker:
def __iter__(self):
return self
class next_maker():
def __next__(self,):
self.count+=1
if self.count > self.limit:
raise StopIteration
return self.count ** 2
class sq(iter_maker, next_maker):
def __init__(self, limit):
self.count = 0
self.limit = limit
所以,当我创建一个实例时:
w = sq(10)
和:
print(list(w))
print(list(w))
我明白了:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[]
但我想要:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
我认为__iter__ 方法每次使用它时都必须返回新对象,但我不知道该怎么做。
谢谢!
【问题讨论】:
标签: python class methods iterator generator