【问题标题】:Why does this class method generate a TypeError?为什么这个类方法会产生 TypeError?
【发布时间】:2022-09-23 04:52:14
【问题描述】:

我正在编写一个类来创建一个数学序列,但是,当我调用类方法getValueRangegetValueList 时,我得到一个TypeError,似乎是附加到nums 列表。

这是类定义:

class Sequence:
    def __init__(self, term: str, var: str):
        self.term = term
        self.var = var

    def getValueAt(self, pos: int) -> int:
        return int(eval(self.term.replace(self.var, str(pos))))

    def getValueRange(self, pos1: int, pos2: int) -> list:
        nums = []

        for i in range(pos1, pos2):
            nums += self.getValueAt(i)

        return nums

    def getValueList(self, pos_list: list):
        nums = []

        for i in pos_list:
            nums += self.getValueAt(int(i))

        return nums


sq = Sequence(\"5*x-6\", \"x\")
print(sq.getValueAt(1))
print(sq.getValueAt(2))
print(sq.getValueRange(4, 44))
print(sq.getValueList([5, 9, 27]))

这是我的错误:

  File \"C:\\Users\\USERNAME\\PycharmProjects\\Wistfully\\main.py\", line 29, in <module>
    print(sq.getValueRange(4, 44))
  File \"C:\\Users\\USERNAME\\PycharmProjects\\Wistfully\\main.py\", line 13, in getValueRange
    nums += self.getValueAt(i)
TypeError: \'int\' object is not iterable

我已经尝试在两个函数中注释掉附加到 nums 列表中,然后打印出结果,效果很好。我调试了所有变量,而且我肯定遗漏了一些东西。

  • list += int 不附加到 list。它引发了TypeError。追加使用list.append(int)nums.append(self.getValueAt(i))

标签: python class sequence


【解决方案1】:

nums += self.getValueAt(int(i)) 更改为nums.append(self.getValueAt(int(i)))。使用+= 将项目附加到列表仅在您要附加的项目在列表中时才有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-19
    • 1970-01-01
    • 2012-08-08
    • 1970-01-01
    • 2013-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多