1

In Python 3, I have a list of classes, and each class has a list in it. I'm having difficulties updating those lists. As so:

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)

The function SomeFunction() is an elaborate function that retrieves a different value for each Item instance.

For some reason, each Item instance in the items list has the same value for prices, which is a list that contains the newPrice value for each Item instance. I hope this is clear enough.

What am I missing?

Phil
  • 23
  • 3
  • You know, at first I didn't think so because I didn't quite understand what that poster was asking, but after reading Eugene's answer, it makes much more sense. You are correct. Thanks. – Phil Oct 16 '15 at 17:48

1 Answers1

0

You should define prices as instance attribute, instead of class attribute, because class attributes are shared between all instances:

class Item():

    def __init__(self, _prices):
        self.newPrice = 0
        self.price = _prices
Eugene Soldatov
  • 9,755
  • 2
  • 35
  • 43