I have a simple data store object which uses a dictionary. When I create two instances of this object it seems the store dictionary is being treated as a static variable and the second object overwrites the first. However, the value variable in the class is not static. Here is a simple code example:
class Obj():
store = {}
value = None
def __init__(self, id, name, value=None):
self.store["Id"] = id
self.store["Name"] = name
self.value = value
def __getitem__(self, item):
return self.store[item]
def __str__(self):
return f'{self["Id"]}:{self["Name"]} {self.value}'
obj1 = Obj(5680, "Dimmer", 100)
obj2 = Obj(5681, "ON/OFF", True)
print(obj1)
print(obj2)
What I get is this:
> 5681:ON/OFF 100
> 5681:ON/OFF True
But if I change where I define my store dictionary to the __init__
method, it works:
class Obj():
value = None
def __init__(self, id, name, value=None):
self.store = {}
self.store["Id"] = id
self.store["Name"] = name
self.value = value
And the output is this:
> 5680:Dimmer 100
> 5681:ON/OFF True
I don't understand why in my first example it is treating the store dictionary as 'static'.
OK - It seems my store attribute is a 'class attribute' - REF: https://www.toptal.com/python/python-class-attributes-an-overly-thorough-guide
However, my value attribute is being treated as a 'instance attribute' as it is assigned a non-mutable value (None/Integer etc)