【发布时间】:2022-01-10 16:36:08
【问题描述】:
在这段代码中,为什么当我在 x1 = Chain ("6") 中放入一个字符串“6”而不是 6 时,它会在执行时打印一个无限数?
class Chain:
def __init__(self, n):
self.n = n
self.counter = 0
def __next__(self):
if self.counter != self.n:
self.counter += 1
else:
raise StopIteration
return self.counter
def __iter__(self):
return self
x1 = Chain("6")
for i in x1:
print(i)
【问题讨论】:
-
因为 int
self.counter永远不会等于字符串“6”。整数不等于字符串。 -
您是否将 6 作为字符串传递?应该是一个整数
标签: python python-3.x iteration iterable