0

I am defining some base class, and i want to add dict variable with default values to it like this:

class A(object):
     d = {'a':None, 'b': None}
     def __init__(self, data):
         self.data=data

The problem is: when in one of the instances interacts with dict d, it affects all instances. Here is an example:

In [109]: f = A([1,2,3])

In [110]: ff = A([4,5,6])

In [111]: f.d['a']="hello"

In [112]: ff.d
Out[112]: {'a': 'hello', 'b': None}

Is there a way to declare this variable in the base class so that when changed it will not affect other instances of the class?

Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
Farseer
  • 4,036
  • 3
  • 42
  • 61

1 Answers1

2

The most likely way to do this is to declare your dictionary of defaults as an instance variable. It can then be accessed and modified by each instance without affecting the other.

class A(object):

     def __init__(self, data):
         self.data = data
         self.d = {'a':None, 'b':None}
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80