这里是我的代码:的Python:迭代器返回无
class Prizes(object):
def __init__(self, purchases, n, d):
self.p = purchases
self.n = n
self.d = d
self.x = 1
def __iter__(self):
return self
def __next__(self):
print(self.x)
if self.x % self.n == 0 and self.p[self.x - 1] % self.d == 0:
self.x = self.x + 1
return self.x - 1
elif self.x > len(self.p):
raise StopIteration
self.x = self.x + 1
def superPrize(purchases, n, d):
return list(Prizes(purchases, n, d))
用法的例子:
superPrize([12, 43, 13, 465, 1, 13], 2, 3)
输出应该是:
[4]
但实际输出为
[None, None, None, 4, None, None].
为什么会发生?
你的问题是你的'__next__'的实现。当Python调用'__next__'时,它总会期望返回值。然而,就你而言,看起来你可能并不总是每个呼叫都有一个返回值。因此,Python使用函数的默认返回值 - 'None'。 –
制作这个'Prizes'迭代器有什么意义? –
另外,我想补充一句,你在这里问你的第一个问题做得很好。你做的一切都正确。您提供了[mcve],发布了您的预期输出,并将您的实际内容发布出去。正因为如此,你得到了(希望)有用的答案。恭喜。 –