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

后端 未结 2 505
猫巷女王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条回答
  •  青春惊慌失措
    2021-01-18 15:43

    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

    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
    

提交回复
热议问题