0

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)

Phil Ware
  • 19
  • 4
  • 1
    Get rid of class variable declarations `store = {}` and `value = None`. You are declaring them in the constructor, that's good enough. – goodvibration Nov 28 '19 at 10:40

3 Answers3

2

In here, you have:

class Obj():
    value = None # class-level variable

    def __init__(self, value=None):
        self.value = value # object-level variable

Therefore, you have:

  • Obj.value, which is a class-level variable (common to all Obj instances)
  • obj.value, which is an object-level variable of obj, where obj is an instance of type Obj
goodvibration
  • 5,980
  • 4
  • 28
  • 61
1

Because in you first example the variable are class attribute so they are common to all the class not the instance.

This article explain it very well https://www.toptal.com/python/python-class-attributes-an-overly-thorough-guide

Best regards

TOTO
  • 307
  • 1
  • 6
1

In python any variables which are assigned a value in the class declaration are static whereas any variables which are assigned values inside class methods are instance variables.

See here for additional detail.

zackck
  • 76
  • 6