2

I am a Python noobie, and I'm experiencing some problems with grasping how does the dictionary work in Python.

I created a class:

class Test:
    dictionary = dict()

    def __init__(self, id):
        self.id = id

    def add(self, key, val):
        self.dictionary[key] = val

    def print(self):
        print("id: " + str(self.id))
        print(self.dictionary.items())

I am executing this code:

list = [Test(0), Test(1)]
list[0].add(0, 0)
list[1].add(1, 1)

for t in list:
    t.print()

The desired effect of this code is to get:

id: 0
dict_items([(0, 0)])
id: 1
dict_items([(1, 1)])

But instead I get:

id: 0
dict_items([(0, 0), (1, 1)])
id: 1
dict_items([(0, 0), (1, 1)])

Why does this happen? And what should I do to get the desired effect? It seems that the dictionary shares the same memory despite it belonging to two different instances of the same class.

Nexon
  • 326
  • 1
  • 11
  • Because, a class attribute is shared by all instances, whereas, instance attribute is specific to that instance. – Austin Nov 02 '18 at 14:42

2 Answers2

0

That's because dictionary is a class attribute. Make it an instance attribute.

Take a look at What is the difference between class and instance attributes?.

class Test:
    def __init__(self, id):
        self.id = id
        self.dictionary = dict()
Dušan Maďar
  • 9,269
  • 5
  • 49
  • 64
0

You are declaring a dictionary as attribute of the class, but you want it as attribute of the instances:

class Test:

    def __init__(self, id):
        self.id = id
        self.dictionary = {}
...
Netwave
  • 40,134
  • 6
  • 50
  • 93