【发布时间】:2018-11-27 15:55:09
【问题描述】:
我的程序有点问题,这里是代码
children_and_parents = {}
class Parent_Child:
def __init__(self, parent, child):
self.parent = parent
self.child = child
def read_data(filename):
with open(filename) as f:
parent, child = line.rstrip("\n").split("->")
children_and_parents[parent] = Parent_Child(parent, child)
问题出在文件中,例如我有超过 1 个孩子的父母:
玛丽->帕特里夏
玛丽->丽莎
但是当我打电话给 children_and_parents["Mary"].child 时,我只得到 Lisa,但我应该得到 Patricia 和 Lisa,而且我希望他们成为不同的“实体”,以便我以后可以调用并使用它们
【问题讨论】:
-
您将玛丽的孩子从帕特里夏改写到丽莎,即帕特里夏被剥夺了身份。我的建议是让
self.child = []成为您附加到的列表。 -
看起来
children_and_parents是一个数组,所以你添加了children_and_parents['xxx'] will only contain the last singleParent_Child` 对象。 -
这是一本字典,children_and_parents = {},添加到问题中,对不起我的错误
-
如果这就是它所包含的全部,这个类似乎有点矫枉过正。我会使用带有字符串键(父)的字典映射到值字符串数组(子)。
标签: python python-3.x object