【发布时间】: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