0

In Python 3.8.3, I created a simple class that contains a dictionary as follows:

class trees:

    fruits = {}
 
    def __init__(self, initFruits = {}):
        self.fruits = initFruits

    def printFruits(self):
        for f in self.fruits:
            print(f, self.fruits[f])

Next, I call the class to create an empty object, and populate it

marigold = trees()
marigold.fruits["apple"] = 3
marigold.printFruits()

Printing the contents gives the expected: apple 3

However, I then want to create another empty object

riverdale = trees()
riverdate.printFruits()

Printing the contents gives me the same out as the Marigold object: apple 3

Furthermore, when I add more items into the Riverdale object, the Marigold object gets altered as well

riverdale.Fruits["orange"] = 5
marigold.printFruits()

Its contents become:

apple 3
orange 5

I wanted to create a separate object, why are they somehow linked?

sekwjlwf
  • 309
  • 3
  • 8
  • The reason it happens is because when the interpreter reads through your definition of your code and comes to this row `def __init__(self, initFruits = {}):` it will then create an empty dictionary there. However it will always point to the same dictionary. Change that to `initFruits=None` and then check inside of the method for `None` and create an empty dictionary instead. – Hampus Larsson Jul 19 '20 at 11:36
  • Duplicate: https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument – Paul M. Jul 19 '20 at 11:37
  • Default arguments are evaluated *once* at function definition time. Note also, your `fruits = {}` in the class body is totally pointless. It creates a *class variable* which gets shadowed by your instance variable in `__init__`. See [this question](https://stackoverflow.com/questions/1680528/how-to-avoid-having-class-data-shared-among-instances). You should take a look at the [official tutorial / docus on python class definitions](https://docs.python.org/3/tutorial/classes.html) – juanpa.arrivillaga Jul 19 '20 at 11:37
  • Thank you for the explanations and help! I tried searching for the answer but didn't get the keywords right. Hope my question here can help direct other beginners to the previously answered posts. – sekwjlwf Jul 19 '20 at 11:52

0 Answers0