我动态地将新值添加到字典中。当我调用它时,我希望它能够加载最近添加的值。
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}
答案 0 :(得分: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.
因此,您要从新创建的dict
对象中打印Element
值,并且它与您更新的对象无关。
要解决此问题,您只需要引用1个对象。
ele = Elements(100)
print ele.dict
print ele.dict_update()
print ele.dict
答案 1 :(得分:-1)
试试这个:
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