Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 977
Yogesh Yadav Avatar asked Feb 15 '26 23:02

Yogesh Yadav


2 Answers

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.

like image 108
Akshat Mahajan Avatar answered Feb 17 '26 12:02

Akshat Mahajan


You have defined children as class variable instead of instance variable. If you change it to instance variable instead it will behave as you would expect:

class Example:
    def __init__(self):
        self.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

# Output: instance2_child1 -> Instance 2 child 1
like image 31
niemmi Avatar answered Feb 17 '26 12:02

niemmi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!