python中属性的子属性

python中属性的子属性,python,class,dictionary,attributes,Python,Class,Dictionary,Attributes,类似的问题,我想知道在python中实现属性属性的正确/常见方法是什么。或者我已经错了这样的想法。以下是一些例子: 方法1 很明显,它不允许self.father.height class household: def __init__(self, address, name0, height0, name1,height1 ): self.address = address self.father.name = name0 self.fa

类似的问题,我想知道在python中实现属性属性的正确/常见方法是什么。或者我已经错了这样的想法。以下是一些例子:

方法1

很明显,它不允许
self.father.height

class household:
    def __init__(self, address, name0, height0, name1,height1 ):
        self.address = address
        self.father.name = name0
        self.father.height = height0
        self.mother.name = name1
        self.mother.height = height1

household("198 Ave", "John", 6.4, "Jean",5.2)

output:
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-180-09f6784cb40e> in <module>
----> 1 household("198 Ave", "John", 6.4, "Jean",5.2)

<ipython-input-179-9ccb52cdb476> in __init__(self, address, name0, height0, name1, height1)
      2     def __init__(self, address, name0, height0, name1,height1 ):
      3         self.address = address
----> 4         self.father.name = name0
      5         self.father.height = height0
      6         self.mother.name = name1

AttributeError: 'household' object has no attribute 'father'

方法1不起作用的原因与错误消息给出的原因完全相同:无法为不存在的属性创建子属性。您必须将self.father初始化为具有兼容结构的东西;然后,您可以将属性分配给子属性

分配dict是实现预期结果的一个非常好的方法

如果要实现这一点,我会将name/height对作为条目的列表或元组,以便以后扩展。有些人有单亲;其他人有两个以上

household("198 Ave", [("John", 6.4), ("Jean",5.2)] )

似乎你可以得到一些接近你想要使用的东西:

例如:

h = household("198 Ave", "John", 6.4, "Jean",5.2)
print(h.father.name, h.father.height)
它给出:

John 6.4

您需要做的是,首先需要初始化self.father,然后使用self.father.name


您还应该阅读python文档中关于OOP的更多内容,我不知道哪种方法是实现OOP的典型/常用方法。但是当然,我们可以让方法1起作用@Angadsingbedi是对的,我们可以使用
类型(“,(),{})”将
self.father
初始化为有效对象。有关创建空对象的详细信息,请参见


您可以阅读python中的类和面向对象编程,这将在这种情况下对您有所帮助:也许,创建一个父类并将这些对象传递到列表中,然后将列表保存在attibute name parents中。非常感谢您分享您的知识
h = household("198 Ave", "John", 6.4, "Jean",5.2)
print(h.father.name, h.father.height)
John 6.4
class household:
    def __init__(self, address, name0, height0, name1,height1 ):
        self.address = address
        self.father = type("person", (),{})()
        self.father.name = name0
        self.father.height = height0
        self.mother = type("person", (), {})()
        self.mother.name = name1
        self.mother.height = height1

house0 = household("198 Ave", "John", 6.4, "Jean",5.2)
house0.father.name
# John