如何将父母与子女彼此联系起来? [英] How to link parent and children to each other?

查看:70
本文介绍了如何将父母与子女彼此联系起来?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有两个简单的类;一个仅具有 parent 属性,另一个具有 parent children 属性。
这意味着同时有父母孩子的父母从只有<$ c $的父母继承c> parent 。

Having two simple classes; one with only parent attribute, and one with both parent and children attributes. This means that the one with both parent and children inherits from the one with only parent.

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

Here's the class with only parent attribute. Let's call it Child since it can only be a child, not a parent. I'll use a method set_parent() to make it more clear, but I would use a setter in my actual code.

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)

该代码很合理,而且看起来也很好。
这是如果 Parent 类看起来像这样简单:

The code makes perfect sense and seems to work just fine. This is, if the Parent class looks as simple as this:

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)

但是,我希望能够呼叫 my_parent.add_child(my_child)并拥有 my_child 的父级属性设置为 my_parent ,同时从其旧父级的子级中删除 my_child

However, I want to be able to call my_parent.add_child(my_child) and have my_child's parent attribute set to my_parent while removing my_child from it's old parent's children.

我似乎无法弄清楚如何真正设计代码,我尝试的一切都会变成之间的无限循环set_parent() add_child() remove_ child()

I can't seem to figure out how to actually design the code, everything I try will turn into an infinite loop between set_parent() and add_child() or remove_child().

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

I know this site is not meant for other people to write code for me, but could someone at least give some hints? My brain just can't handle this problem, I've been thinking for 30 minutes straight and haven't gotten anything done. Help appreciated!

推荐答案

您在做什么都是胡说八道。
只需将它们设为一类,并使用 add_child() remove_child() set_parent(),但不能同时使用两者。

What you're doing is nonsense. Just make them one class and use either add_child() and remove_child() or set_parent(), but not both.

这篇关于如何将父母与子女彼此联系起来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆