add items to the list of an object

Viewed 307
class bag:

    items = []

    def add_item(self,x):
        self.items.append(x)


if __name__ == "__main__":

    bag1 = bag()
    bag2 = bag()

    bag1.add_item("water")
    print(bag2.items)
    

I'm trying to add water to the bag1 but I have no idea why "bag1.add_item("water")" will affect bag2

3 Answers
class bag:

    def __init__(self):
        self.items = []

    def add_item(self,x):
        self.items.append(x)


if __name__ == "__main__":

    bag1 = bag()
    bag2 = bag()

    bag1.add_item("water")
    print(bag2.items)

All you have to do is add def __init__(self). Declaring the variables inside the class declaration makes them "class" members and not instance members. Declaring them inside the __init__ method makes sure that a new instance of the members is created alongside every new instance of the object, which is the behavior you're looking for.

Notice that items = [] has been declared as a class variable, so all instances of that class will share the same memory location for items. For each instance to have it's own items list, you need to use the keyword self, something like:

class bag:

    def __init__(self):
        self.items = []

    def add_item(self,x):
        self.items.append(x)


if __name__ == "__main__":

    bag1 = bag()
    bag2 = bag()

    bag1.add_item("water")
    print(bag2.items)

For additional details, refer to this documentation.

The following code should fix the problem:

class bag:

    def __init__(self):
        self.items = []

    def add_item(self, x):
        self.items.append(x)


if __name__ == "__main__":
    bag1 = bag()
    bag2 = bag()

    bag1.add_item("water")
    print(bag2.items)

Related