我有一个应该在给定间隔内打印方块的函数:
class Squares:
def __init__(self, min, max):
self.min = min
self.max = max
def __iter__(self):
return self
def __next__(self):
a_list = []
for i in range((self.max)+1):
a_list += [i**2]
if self.min <= self.max:
if self.min in a_list:
result = self.min
self.min += 1
return result
else:
self.min += 1
else:
raise StopIteration
import math
for i in Squares(5, 50):
print(i)
它应该打印9,16,25,49,但输出是:
None
None
None
None
9
None
None
None
None
None
None
16
None
None
None
None
None
None
None
None
25
None
None
None
None
None
None
None
None
None
None
36
None
None
None
None
None
None
None
None
None
None
None
None
49
None
为什么会这样?
答案 0 :(得分:0)
每次变量结果不是正方形时返回 None 的原因是,如果没有指定返回,则next()函数默认返回 None
如果必须为此项目使用迭代器,则必须构造代码,以便每次传递都返回一个值。
另外,请注意,每次调用next()时,都会生成一个名为a_list的全新数组,效率非常低。初始化该数组一次会好得多。
查看此示例中的差异。
class Squares:
def __init__(self, min, max):
self.min = min
self.max = max
def __iter__(self):
self.a_list = []
for i in range((self.max)+1):
self.a_list += [i**2]
self.iter_index = 0
return self
def next(self):
self.iter_index += 1
if self.a_list[self.iter_index] > self.max:
raise StopIteration
else:
return self.a_list[self.iter_index]
import math
import pdb
for i in Squares(5, 50):
print(i)