I have a class called SalesSimulator that has an attribute called common_params that is a dict. It contains a key named number_agents which points to an integer value.
The values of the dict have values that are drawn during `init' procudure from another file file called SimulatorObjects which contains the default values fed to the SalesSimulator.
The user of the class may inspect this attribute and if necessary change the value from the default to their own preference. This all works ok. What I am finding odd is that if I create one instance of the class and set a new value for one of the items in the attribute common_params that value feeds through to all future instances of the class.
For example:
ss = SalesSimulator()
print(ss.common_params['number_agents'])
ss.common_params['number_agents'] = 10
print(ss.common_params['number_agents'])
so far so good. But now if I create a new instance of the class:
new_ss = SalesSimulator() print(new_ss.common_params['number_agents'])
I was expecting that for a new instance of the class the value would go back to 1, which is the default value that is called in during the SalesSimulator constructor.
Here is the relevant part of that constructor:
import SimulatorObjects as so #this is my file of default values
class SalesSimulator(object):
def __init__(self):
# some other stuff happens here that is not relevant
# set default parameters
self.common_params = so.common_params
The item in the SimulatorObject file looks like this:
common_params = {'number_agents': 1,
'other_stuff': [],
'some_factor': 1.4}
It seems I can get around the problem by doing:
self.common_params = copy.deepcopy(so.common_params)
Is that an acceptable solution?