0

I created a class to store some variables and dictionary. Each object will have its own dictionary. However when I created a Class in certain way, it resulted in dictionary getting shared across all objects created. When I tweaked the init, I was able to achieve what I wanted. I want to know why dictionary got shared across different objects and when and I would that be useful.

Snippet 1: (Where dictionary gets populated and shared across all object instances)

class A(object):
    def __init__(self, x, y={}):
        self.x = x
        self.y = y

    def set_y(self,key,value):
        self.y[key] = value

Snippet 2:(Where dictionary value is unique and not shared between member instances)

   class A(object):
        def __init__(self,x):
            self.x = x
            self.y = {}

        def set_y(self,key,value):
            self.y[key] = value

Test Driver:

l = "abcdefghijklmnopqrsqtuwxyz"
letter_list = []
node = None
for count, letter in enumerate(l,1):
    if node:
        letter_list.append(node)
    node = A(letter)
    node.set_y(letter,count)

I would like to know why dictionary got updated for all instances in first case and not for the second case

Ani
  • 149
  • 1
  • 1
  • 8

1 Answers1

1

The dictionary is updated because of the way you used the default value in the __init__ constructor. In the first case, that empty dict is a single object; it is not a unique constructor for each new object. It gets evaluated when the class is defined, and the same dict object sits there for each new object instantiated. Very simply, the line

def __init__(self, x, y={}):

is executed once, when the function is defined, during the class definition.

In your second case, the initialization self.y = {} is in the body of the function, and so gets executed each time you instantiate a new object. You can see the longer explanation in this canonical posting on the topic.

Prune
  • 76,765
  • 14
  • 60
  • 81