【问题标题】:Python, update initialized dictionary that works as class attributePython,更新用作类属性的初始化字典
【发布时间】:2017-10-18 00:00:00
【问题描述】:

我动态地将新值添加到字典中。当我调用它时,我希望它会加载最近添加的值。

class Elements():
    def __init__(self, length):
        self.dict = {}
        self.length = length
        self.init_dict()

    def init_dict(self):
        self.dict[0] = self.length
        return self.dict[0]

    def dict_update(self):
        self.dict.update({1: self.dict[0] + 1})
        return self.dict

Elements(100)
print Elements(100).dict
print Elements(100).dict_update()
print Elements(100).dict

这会返回: {0: 100}, {0: 100, 1: 101}, {0: 100}

而我期待 {0: 100}, {0: 100, 1: 101}, {0: 100, 1: 101}

【问题讨论】:

  • 你在每一行都创建了一个新对象。
  • 顺便说一句,不要使用self.dict.update 来更新单个值。使用self.dict[k] = value 之类的self.dict[1] = self.dict[0] + 1
  • 如果您希望dict 属性成为类属性,为什么不将其创建为一个?只需将dict = {} 放在类的顶层(不在方法内)并从__init__ 中删除等效行。通常这不是你想要的,但它似乎正是你想要的。

标签: python class dictionary


【解决方案1】:

让我解释一下:

Elements(100) # New element created.
print Elements(100).dict # Print dict from a new element created.
print Elements(100).dict_update() # Print what is returned from dict_update from a new element created. In this case, the dict is updated as well.
print Elements(100).dict # Print dict from a new element created. So this object is not related to the old updated one.

所以您正在从新创建的Element 对象打印dict 值,它与您更新的对象无关。

要解决此问题,您只需引用 1 个对象。

ele = Elements(100)
print ele.dict
print ele.dict_update()
print ele.dict

【讨论】:

    【解决方案2】:

    试试这个:

    class Elements():
        def __init__(self, length):
            self.dict = {}
            self.length = length
            self.init_dict()
    
        def init_dict(self):
            self.dict[0] = self.length
            return self.dict[0]
    
        def dict_update(self):
            self.dict.update({1: self.dict[0] + 1})
            return self.dict
    
    E = Elements(100)
    print E.dict
    print E.dict_update()
    print E.dict
    

    【讨论】:

      猜你喜欢
      • 2017-09-29
      • 1970-01-01
      • 1970-01-01
      • 2021-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多