Python: Derived Classes Access Dictionary Of Base Class In The Same Memory Location
Solution 1:
It's because _testdict
is a class variable: it's defined only once, when the class is initially constructed. If you want it to be separate for each instance, make it an instance variable:
classBaseClass:
_testint = 0def__init__(self):
self._testdict = dict()
defadd_dict_entry(self):
self._testdict["first"] = 1
(Note that you'd need to create __init__
methods for Class1
and Class2
as well, both of which would have to call BaseClass.__init__(self)
).
_testint
behaves differently because you're performing a rebinding operation on it rather than a mutating operation. ints are immutable, so you can't "change" one- self._testint += 1
is just syntactic sugar for self._testint = self._testint + 1
. Similarly, you can perform a rebinding operation on self._testdict
that won't be shared between instances- for example, self._testdict = {}
will reset only that instance's _testdict
.
Solution 2:
In python, int is immutable, therefore the += operation will rebound the class variable into an instance variables. On the other hand, a dictionary indexing mutates the dictionary in place. A more comparable example would be
defadd_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
Post a Comment for "Python: Derived Classes Access Dictionary Of Base Class In The Same Memory Location"