Avo*_*yan 5 python iterator class generator nonetype
这是我的代码:
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))
Run Code Online (Sandbox Code Playgroud)
用法示例:
superPrize([12, 43, 13, 465, 1, 13], 2, 3)
Run Code Online (Sandbox Code Playgroud)
输出应该是:
[4]
Run Code Online (Sandbox Code Playgroud)
但实际输出是:
[None, None, None, 4, None, None].
Run Code Online (Sandbox Code Playgroud)
为什么会这样?
你的问题是你的实现__next__。当Python 调用时__next__,它总是期望有一个返回值。但是,就您而言,每次调用似乎并不总是有返回值。因此,Python 使用函数的默认返回值 - None:
您需要某种方法来将程序控制保持在内部,__next__直到获得实际的返回值。这可以使用 -loop 来完成while:
def __next__(self):
while True:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1429 次 |
| 最近记录: |