如何在 Python 中创建可重复使用的生成器 类?
How to create reusable generator classes in Python?
我需要创建可以多次使用的生成器。我有 类 这样的:
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__
方法必须 return 新对象每次我使用它,但我不知道该怎么做。
谢谢!
这取决于你想如何使用它。如果正如上面概述的那样(或类似的)那么这应该有效:
class sq:
def __init__(self, limit):
self.limit = limit
def __iter__(self):
yield from (n**2 for n in range(1, self.limit + 1))
这个
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]
我需要创建可以多次使用的生成器。我有 类 这样的:
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__
方法必须 return 新对象每次我使用它,但我不知道该怎么做。
谢谢!
这取决于你想如何使用它。如果正如上面概述的那样(或类似的)那么这应该有效:
class sq:
def __init__(self, limit):
self.limit = limit
def __iter__(self):
yield from (n**2 for n in range(1, self.limit + 1))
这个
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]