0

I am facing a curious problem in Python which I believe is somehow related to the class dictionary vs. instance dictionary behaviour.

Let's say I would like to have a list of my objects, each one has an instance dictionary that I would like to modify. The code below works as intended and will be my baseline example:

class TestObject():

    def __init__(self):
        self.test_dict = {}

test_list = []
test_list.append(TestObject())
test_list.append(TestObject())

test_list[0].test_dict["key"] = "value"

print(test_list[0].test_dict)
# Output: {'key': 'value'}
print(test_list[1].test_dict)
# Output: {}

Now I want to be able to pass a test_dict while keeping a default empty dict. My first thought was to write the following:

class TestObject():
    def __init__(self, test_dict = {}):
        self.test_dict = test_dict

test_list = []
test_list.append(TestObject())
test_list.append(TestObject())

test_list[0].test_dict["key"] = "value"

print(test_list[0].test_dict)
# Output: {'key': 'value'}
print(test_list[1].test_dict)
# Output: {'key': 'value'}

As you can see, the output is not really expected since key/value pair seems to have been assigned to the class dict instead of the instance dict. Am I even right about it?

And the last test which doesn(t seem to make any sense to me is to pass an empty dict when initiate each object:

class TestObject():
    def __init__(self, test_dict = {}):
        self.test_dict = test_dict

test_list = []
test_list.append(TestObject(test_dict = {}))
test_list.append(TestObject(test_dict = {}))

test_list[0].test_dict["key"] = "value"

print(test_list[0].test_dict)
# Output: {'key': 'value'}
print(test_list[1].test_dict)
# Output: {}

And everything seems to work as expected again. I am more confused that you could imagine.

My question is: what happens behind the stage for these dict key/value pairs assignments? Is there a way to initiate an object with an instance dictionary nd allow a default value for it?

Many thanks in advance!

0 Answers0