Python class referencing

3552 views python

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):

   inventory = []

bags = []   #List of all bags   

#Create bags
my_bag = bag()

toms_bag = 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?

answered question

inventory is a class variable, not an instance variable, thus all instances of this class share the same variable.

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.

1 Answer


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):

posted this

Have an answer?


Please login first before posting an answer.