【问题标题】:Why does this code print infinite numbers? [closed]为什么这段代码会打印出无穷大的数字? [关闭]
【发布时间】: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


【解决方案1】:

这一行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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多