0

I tried to create two objects that both have their own inventories. As far as I'm concerned I successfully managed to create two different objects called my_bag and toms_bag This is the code I used

class bag(object):
   def inventory_add(self, item):
      self.inventory.append(item)

   inventory = []

bags = []   #List of all bags   

#Create bags
my_bag = bag()
my_bag.inventory_add("pencil")
bags.append(my_bag)

toms_bag = bag()
toms_bag.inventory_add("book")
bags.append(toms_bag)

for bag in bags:    #Print inventories
   print(bag, bag.inventory)

This is the result I get.

<__main__.bag object at 0x004D0830> ['pencil', 'book']
<__main__.bag object at 0x004D0790> ['pencil', 'book']

So why are the items added to both of their inventories? Are they even different objects now?

Lolman
  • 107
  • 8
  • 1
    ``inventory`` is a class variable, not an instance variable, thus all instances of this class share the same variable. – Mike Scotty Nov 06 '18 at 15:52
  • With `inventory = []`, you are declaring a variable in the class itself, no in objects created from this class, which means the variable `inventory` will be common to all your objects. – Cyphall Nov 06 '18 at 15:56

1 Answers1

2

Your syntax looks like you're coming from C#, Java, C++, or some other more strictly OOP language. The way to do what you want in Python is to initialize the inventory array in the class constructor:

class bag(object):
    def __init__(self):
        self.inventory = []

    def inventory_add(self, item):
       self.inventory.append(item)
scnerd
  • 5,836
  • 2
  • 21
  • 36