0

I think my problem lies within my comprehension of how Python handle Objects. Here is the code that produce my "bug":

a1 = A("my name is A1")
a2 = A("my name is A2")
a1.add_b("my name is B1")
a1.add_b("my name is B2")

print "for {0} the content of b_dict is: {1}".format(a1.name, a1.b_dict)
print "for {0} the content of b_dict is: {1}".format(a2.name, a2.b_dict)


class A():
    name = ''
    b_dict = {}

    def __init__(self, name_of_a):
        self.name = name_of_a

    def add_b(self, name_of_b):
        self.b_dict[name_of_b] = B(name_of_b)
        return


class B():
    name = ''

    def __init__(self, name_of_b):
        self.name = name_of_b

Now, the print result is:

for my name is A1 the content of b_dict is: {'my name is B1': <__main__.B instance at 0x7f0db0e5bdd0>, 'my name is B2': <__main__.B instance at 0x7f0db0e5be18>}
for my name is A2 the content of b_dict is: {'my name is B1': <__main__.B instance at 0x7f0db0e5bdd0>, 'my name is B2': <__main__.B instance at 0x7f0db0e5be18>}

I don't understand why by adding B objects into the b_dict dictionary of a1, I somehow manage to add the same objects to the b_dict dictionary of a2. Please enlighten me as to why it is happening.

Thank you for your time.

Andy G
  • 19,232
  • 5
  • 47
  • 69

2 Answers2

0
class A():
   #intialise ur values at init.

    def __init__(self, name_of_a):
        self.name=''
        self.b_dict={}
        self.name = name_of_a

    def add_b(self, name_of_b):
        self.b_dict[name_of_b] = B(name_of_b)
        return


class B():
    name = ''

    def __init__(self, name_of_b):
        self.name = name_of_b
a1 = A("my name is A1")
a2 = A("my name is A2")
a1.add_b("my name is B1")
a2.add_b("my name is B2")

print "for {0} the content of b_dict is: {1}".format(a1.name, a1.b_dict)
print "for {0} the content of b_dict is: {1}".format(a2.name, a2.b_dict)
sundar nataraj
  • 8,524
  • 2
  • 34
  • 46
0

b_dict is a class-level variable, so it is common to all instances of the class. To have instance-specific copies of b_dict, you have to write self.b_dict = {} in the class __init__ method.

PaulMcG
  • 62,419
  • 16
  • 94
  • 130