【问题标题】:Updating a list in a class, in a list [duplicate]在列表中更新类中的列表[重复]
【发布时间】:2023-03-25 08:24:01
【问题描述】:

在 Python 3 中,我有一个类列表,每个类都有一个列表。我在更新这些列表时遇到了困难。因此:

class Item():
    newPrice = 0
    prices = [0]
    def __init__(self, _prices):
        self.prices = _prices

items = [Item([10]), Item([20]), Item([30])]
for item in items:
    item.newPrice = SomeFunction()
    item.prices.append(item.newPrice)

函数SomeFunction() 是一个复杂的函数,它为每个Item 实例检索不同的值。

由于某种原因,items 列表中的每个 Item 实例都具有相同的 prices 值,这是一个包含每个 Item 实例的 newPrice 值的列表。我希望这已经足够清楚了。

我错过了什么?

【问题讨论】:

  • 你知道,起初我并不这么认为,因为我不太明白那张海报在问什么,但在阅读了尤金的回答之后,它变得更有意义了。你是对的。谢谢。

标签: python list class python-3.x


【解决方案1】:

您应该将价格定义为实例属性,而不是类属性,因为类属性在所有实例之间共享:

class Item():

    def __init__(self, _prices):
        self.newPrice = 0
        self.price = _prices

【讨论】:

  • 我不敢相信它这么简单。我知道我错过了一些东西。谢谢!
猜你喜欢
  • 2016-05-30
  • 2021-05-20
  • 2016-12-28
  • 1970-01-01
  • 2014-09-26
  • 2015-11-01
  • 2021-02-05
  • 2021-06-18
  • 1970-01-01
相关资源
最近更新 更多