【发布时间】:2018-02-05 05:07:14
【问题描述】:
这是我的代码:
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迭代器有什么意义? -
另外,我可以补充一下,您在这里提出的第一个问题做得很好。你做的一切都是正确的。您提供了minimal reproducible example,发布了您的预期输出,并发布了您的实际输出。正因为如此,你得到了(希望)有用的答案。恭喜。
标签: python class iterator generator nonetype