0

I'm trying to create a tree using dictionary. Here is my code:

class Class1():
    a=0
    d={}
    d.clear()

    class Class2():
        b=0
        def __init__(self,data):
            b=data

    def __init__(self,data):
        a=data
        for j in range(3):
            self.d[j]=self.Class2(j)
            print(j)
            print(self.d.keys())

dict1={}
for i in range(4):
    dict1[i]=Class1(i)

What i get is:

0
dict_keys([0])
1
dict_keys([0, 1])
2
dict_keys([0, 1, 2])
0
dict_keys([0, 1, 2])
1
dict_keys([0, 1, 2])
2
dict_keys([0, 1, 2])
0
dict_keys([0, 1, 2])
1
dict_keys([0, 1, 2])
2
dict_keys([0, 1, 2])
0
dict_keys([0, 1, 2])
1
dict_keys([0, 1, 2])
2
dict_keys([0, 1, 2])

I expect a whole new empty child dict in each father dict, but from the second loop, the dict already have data when created. I checked the object id, the object in second "Class1" object's dict is just those in the first one, and so to the third and fourth one.

This happened on dict object only, other object like string or int are not affected.

Does anyone know why this happen? Thanks.

My Python is 3.6.2

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
qwer11121
  • 138
  • 2
  • 15
  • You are sharing the same dictionary as a class attribute. – Martijn Pieters Aug 17 '17 at 06:51
  • 2
    Because you have `d` at the *class* level - not the *instance* level... move the `d = {}` to be `self.d = {}` inside your `__init__`... – Jon Clements Aug 17 '17 at 06:51
  • Also, there is no advantage to nest a class inside another in Python; there is no privacy model like in Java (where you'd nest a class to give that nested class access to private data). – Martijn Pieters Aug 17 '17 at 06:53
  • You will "hide" `class2` though so that it's more difficult to instantiate from outside `class1`. – Moberg Aug 17 '17 at 06:57

0 Answers0