MerC
MerC

Reputation: 323

What's the difference between defining the key/value pair of a dictionary and defining the dictionary in python?

I have these 2 functions in one class

Class A(object):
    my_dict{"a":1, "b":2, "c":3}

    def set_dict(self,key,value):
    self.my_dict[key] = value

    def set_dict2(self,dict):
    self.my_dict= dict   

Then I create A class objects,

obj1 = A()
obj1.set_dict("a",4)
obj1.set_dict("b",5)
obj1.set_dict("c",6)
obj2 = A()
obj2.set_dict("a",7)
obj2.set_dict("b",8)
obj2.set_dict("c",9)

If I do the above, both obj1 and obj2 has {a:7, b:8, c:9} as in obj1 is also changed by the latest change done to obj2. But it is working ok if do this:

obj1 = A()
obj1.set_dict2({"a":4, "b":5, "c":6})
obj2 = B()
obj2.set_dict2({"a":7, "b":8, "c":9})

So question is what's wrong with doing set_dict()?

Upvotes: 0

Views: 94

Answers (2)

aIKid
aIKid

Reputation: 28352

That's because my_dict is a class variable. When you say my_dict[key] = value, you're modifying the dictionary in the class, not in your variable.

To make it clearer, let's see this console session:

>>> a = A()
>>> a.set_dict('a', 7)
>>> A.my_dict
{'a': 7, 'c': 3, 'b': 2}
>>> n = A()
>>> n.set_dict('a', 10)
>>> A.my_dict
{'a': 10, 'c': 3, 'b': 2}

So, you're changing A.my_dict instead of a.my_dict. To solve this, you need to make it an instance variable:

class A(object):
    def __init__(self):
        self.my_dict = {"a":1, "b":2, "c":3}

    def set_dict(self,key,value):
        self.my_dict[key] = value

    def set_dict2(self,dct):
        self.my_dict = dct

Hope this helps!

Upvotes: 2

Steinar Lima
Steinar Lima

Reputation: 7821

You need to make my_dict an instance variable, such as:

Class A(object):
    def __init__(self):
        self.my_dict{"a":1, "b":2, "c":3}

    def set_dict(self,key,value):
        self.my_dict[key] = value

    def set_dict2(self,dict):
        self.my_dict= dict   

Upvotes: 0

Related Questions