Python access dictionary: base class derived classes in the same memory location

I wonder why a dictionary defined in a base class and accessible from derived classes is explicitly present in only one memory location. A brief example:

class BaseClass:
    _testdict = dict()
    _testint = 0

    def add_dict_entry(self):
        self._testdict["first"] = 1

    def increment(self):
        self._testint += 1

class Class1(BaseClass):
    pass

class Class2(BaseClass):
    pass

object1 = Class1()
object2 = Class2()

object1.add_dict_entry()
object1.increment()
print(object2._testdict)
print(object2._testint)

and output:

{'first': 1}
0

Why does calling the word "add_dict_entry" of object1 affect the dictionary of object2? Using integers ("increment") does not affect the base class variable.

Many thanks.

Lorenz

+5
source share
2 answers

This is because it _testdictis a class variable: it is defined only once when the class was originally built. If you want it to be separate for each instance, make it an instance variable:

class BaseClass:
    _testint = 0

    def __init__(self):
        self._testdict = dict()

    def add_dict_entry(self):
        self._testdict["first"] = 1

( , __init__ Class1 Class2, BaseClass.__init__(self)).

_testint -, , . ints , "" - self._testint += 1 - self._testint = self._testint + 1. , self._testdict, , , self._testdict = {} reset _testdict.

+10

python int , + = . , .

def add_dict_entry(self):
    # create a new dict
    tmp = dict(self._testdict)
    tmp["first"] = 1

    # shadow the class variable with an instance variables
    self._testdict = tmp
+2

All Articles