【问题标题】:Having multiple values under one parameter in objects对象中的一个参数下具有多个值
【发布时间】: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 single Parent_Child` 对象。
  • 这是一本字典,children_and_parents = {},添加到问题中,对不起我的错误
  • 如果这就是它所包含的全部,这个类似乎有点矫枉过正。我会使用带有字符串键(父)的字典映射到值字符串数组(子)。

标签: python python-3.x object


【解决方案1】:

你可以有多个这样的孩子:

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("->")
        if parent in children_and_parents:
            # append the child
            children_and_parents[parent].child.append(child)
        else: 
            children_and_parents[parent] = Parent_Child(parent, child)

这使得孩子成为一个列表,并在创建之前检查父母是否已经存在

【讨论】:

  • 给我一个错误:'Parent_Child' 对象没有属性'append'
  • 我的错。现在应该修好了。我没有访问子属性
【解决方案2】:

猜猜你可以更改以下行

  children_and_parents[parent] = Parent_Child(parent, child)

类似

  children_and_parents.setdefault(parent, []).append(Parent_Child(parent, child))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-05
    • 1970-01-01
    • 2017-03-23
    • 2020-04-05
    • 1970-01-01
    • 2022-06-15
    • 2017-03-27
    相关资源
    最近更新 更多