shiva shiva - 1 year ago 49
Python Question

python dict,list has same instance for all classes

I am working on python 2.7 from last 3 months and I am really surprised after noticing this today.

For the following snippet of code

class Example:
children = {}

instance1 = Example()
instance1.children['instance1_child1'] = 'Instance 1 child 1'

instance2 = Example()
instance2.children['instance2_child1'] = 'Instance 2 child 1'
for key, value in instance2.children.items():
print key + ' -> ' + value

why the output is

instance1_child1 -> Instance 1 child 1
instance2_child1 -> Instance 2 child 1

It seems like there is only one instance of dict() for all the objects I am creating. I checked with list[] also and they are also behaving in the same manner.

I can't understand this behavior of python and what is the logic behind it. Is this some kind of design flaw or am I doing something wrong and deserves to quit programming?

Answer Source

By creating these variables outside the context of a member function, you have unwittingly created a class variable.

Class variables are accessible to every class instance and can be accessed directly from the class itself without instantiating.

Example.children == Example().children
>>> True

Think the equivalent of a global variable defined within a class, and you have your answer.

To correct this, simply place them within the context of __init__.

class Example(object):

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

Now children is bound to the class instance, and not the class itself. Such is the power of self.