【问题标题】:How to add items to a list properly如何正确地将项目添加到列表中
【发布时间】:2021-01-29 10:57:15
【问题描述】:

我目前正在学习 python。我正在学习类、继承和抽象类。这是有问题的构造函数:

def __init__(self, sourceCollection = None):
    """Sets the initial state of self, which includes the
    contents of sourceCollection, if it's present."""
    self.size = 0
    if sourceCollection:
        for item in sourceCollection:
            self.add(item)

我收到以下错误,我不知道为什么:

TypeError: 'int' object is not iterable

如果有帮助,这是我的添加方法:

def add(self, item):
    """Adds item to self."""
    # Check array memory here and increase it if necessary
    
    self.items[len(self)] = item
    self.size += 1

谁能帮助我解决我为什么会收到此错误?我做了一些研究,但无济于事。提前非常感谢!!!

【问题讨论】:

  • 始终提供minimal reproducible example。这意味着我们可以复制和粘贴它并得到相同的确切错误。如果您收到错误消息,总是发布完整的错误消息,包括堆栈跟踪
  • 不要使用self.size来跟踪列表的大小,列表比较清楚,使用len(self.items)

标签: python list class typeerror abstract-class


【解决方案1】:

只要做 (.append()):

def add(self, item):
    """Adds item to self."""
    # Check array memory here and increase it if necessary
    
    self.items.append(item)
    self.size += 1

【讨论】:

    【解决方案2】:

    list 有一个方法可以从一个可迭代对象中添加所有元素

    不要使用self.size来跟踪self.items中的元素数量,使用len(self.items)

    def __init__(self, sourceCollection = None):
        """Make a copy of sourceCollection"""
        self.items = []
        if not sourceCollection: return
        self.items.extend(sourceCollection)
    
    def add(self, item):
        """Adds item to self."""
        self.items.append(item)
    
    @property
    def size(self):
        return len(self.items)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-30
      • 2020-01-30
      • 2021-11-14
      • 1970-01-01
      • 1970-01-01
      • 2018-01-19
      • 1970-01-01
      • 2017-02-20
      相关资源
      最近更新 更多