-1

this is my code:

class Plant:
    def __init__(self,name):
        self.name = name

class Garden:
    def __init__(self,name):
        self.name = name

    list_of_plants = []

list_of_gardens = []
list_of_gardens.append(Garden("garden1"))
list_of_gardens.append(Garden("garden2"))

list_of_gardens[0].list_of_plants.append(Plant("Basil"))

print("Plant1: ", list_of_gardens[0].list_of_plants[0].name)
print("Plant2: ", list_of_gardens[1].list_of_plants[0].name)

Output:

Plant1: Basil
Plant2: Basil

Why does Basil appears in the two nested list? I didn't even affected a value in the second list! Even when I look at the pointers, everything looks good, but append keeps adding values in my other nested lists.

Hugo
  • 1
  • you are missing a `self.` the list in your garden is a shared piece of earth that all gardens have access to - a comminity flower bed ... read [py-tut class and instance variables](https://docs.python.org/3/tutorial/classes.html#class-and-instance-variables) – Patrick Artner Sep 26 '18 at 21:44
  • Thanks for pointing to the right info – Hugo Sep 26 '18 at 21:51

1 Answers1

1

You are assigning list_of_plants to the class, so all class instances will share the same list. You should instead assign it as an attribute of self in the __init__ (i.e. indent 4 more spaces as self.list_of_plants = []) so a new list is created for each individual class instance.

mVChr
  • 49,587
  • 11
  • 107
  • 104