在這段代碼中,為什麼當我在 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)
這一行x1 = Chain("6")
設置self.n = "6"
了一個字符串。在對像中你有counter
一個整數。整數永遠不能等於字符串,因此您self.counter != self.n
總是返回True
並且else
永遠不會進入該塊。
如果我是你,我會將你的修改__init__
為:
def __init__(self, n):
self.n = int(n)
self.counter = 0
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句