1
我想创建一个具有类似生成器的方法的类。我对发电机相当陌生。这里是我的代码:类中的python生成器
class MyGen:
def __init__(self):
self.a = 0
def create_generator(self):
yield self.a
self.a += 1
if __name__ == "__main__":
myGenInstance = MyGen()
myGen = myGenInstance.create_generator()
for i in range(3):
print(next(myGen))
我得到这个错误:
Traceback (most recent call last):
0
File "C:/Users/tvavr/PycharmProjects/filter/geneŕator_test.py", line 17, in <module>
print(next(myGen))
StopIteration
Process finished with exit code 1
我缺少什么?
您的生成器只返回一个值(它只是一个不在任何循环内的yield语句)。试图正确地获得另一个值会导致“StopIteration”异常,表示没有更多的值可以产生。 –
这是非常值得的时间来阅读:http://stackoverflow.com/a/231855/1832539 – idjaw
换句话说:你不会错过任何东西,它的行为完全如预期。 – jonrsharpe