In Python, I instantiate a class twice and store them into 2 different variables. Why does the second object contain a copy of the first object? I know it’s a copy because I change the values in one object and it does not change the other. Example:
I have the following class:
class HistoricalData:
dataPoints = {}
I then instantiate the class and fill dataPoints with values:
hd1 = HistoricalData()
hd1.dataPoints["channel1"] = 1
hd1.dataPoints["channel2"] = 2
hd1.dataPoints["channel3"] = 3
I then instantiate the class again and fill it with values again:
hd2 = HistoricalData()
hd2.dataPoints["channel1"] = 10
When I print the values from hd1.dataPoints and hd2.dataPoints I get the following:
{'channel1': 1, 'channel2': 2, 'channel3': 3}
{'channel1': 10, 'channel2': 2, 'channel3': 3}
The dictionary has a copy of the first in the second object because the value in channel1 was changed in the second but not the first.
I thought when you instantiate a class all values will be defaulted to what was defined in the class. Am I missing something?
You’ve declared a
classvariable, not an instance variable.Class variables are shared among all instances of the
class. This means that when you update oneHistoricalDataobject, you update them all.Instance variables are local to each instance of a
class. These are typically initialised in the__init__()special method, which is called when each instance is created.As such you should probably initialise
datapointslike so to get the results you desire: