如何将父母与子女彼此联系起来?

Ska*_*One 5 python children parent parent-child

有两个简单的类;一个仅具有parent属性,一个同时具有parent和children属性。这意味着,一个既parent和children继承了一个只parent。

这是只有parent属性的类。之所以称呼它,是Child因为它只能是孩子,而不是父母。我将使用一种方法set_parent()使其更加清晰,但在实际代码中将使用setter。

class Child(object):

    def __init__(self, parent=None):
        self.__parent = None
        self.set_parent(parent)

    def set_parent(self, parent):
        # Remove self from old parent's children
        if self.__parent:
            self.__parent.remove_child(self)
        # Set new parent
        self.__parent = parent
        # Add self to new parent's children
        if self.__parent:
            self.__parent.add_child(self)
Run Code Online (Sandbox Code Playgroud)

该代码很合理,并且似乎可以正常工作。这是如果Parent类看起来像这样简单:

class Parent(Child):

    def __init__(self, parent=None):
        super(Parent, self).__init__(parent)
        self.__children = []

    def add_child(self, child):
        if child not in self.__children:
            self.__children.append(child)

    def remove_child(self, child):
        if child in self.__children:
            self.__children.remove(child)
Run Code Online (Sandbox Code Playgroud)

不过,我希望能够调用my_parent.add_child(my_child)和具有my_child的父属性设置为my_parent同时消除my_child从它的老父母的孩子。

我似乎无法弄清楚如何实际设计的代码,一切我尝试将变成之间的无限循环set_parent()和add_child()或remove_child()。

我知道这个网站并不意味着其他人可以为我编写代码,但是至少有人可以提供一些提示吗?我的大脑无法解决这个问题,我已经连续思考了30分钟,却没有做任何事情。帮助赞赏!

小智 1

你所做的就是无稽之谈。只需将它们设置为一个类并使用and add_child()或remove_child() 之一 set_parent(),但不能同时使用两者。