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

后端 未结 2 481
猫巷女王i
猫巷女王i 2021-01-18 15:18

I\'m wondering why a dictionary, that is defined in a base class and is accessed from derived classes, is obviously present only in one memory location. A short example:

2条回答
  •  -上瘾入骨i
    2021-01-18 15:29

    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:

    class BaseClass:
        _testint = 0
    
        def __init__(self):
            self._testdict = dict()
    
        def add_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.

提交回复
热议问题