有两个简单的类;一个只有parent
属性,并且两者兼而有之parent
and children
属性。
这意味着同时具备两者的人parent
and children
继承自唯一的parent
.
这是只有parent
属性。
我们就这样称呼它吧Child
因为它只能是孩子,不能是父母。
我会用一个方法set_parent()
为了使它更清楚,但我会在实际代码中使用设置器。
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
类看起来就像这样简单:
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
来自老父母的孩子。
我似乎不知道如何真正design代码,我尝试的一切都会变成无限循环set_parent()
and add_child()
or remove_child()
.
我知道这个网站不适合其他人为我编写代码,但有人至少可以给出一些提示吗?
我的大脑无法处理这个问题,我已经连续思考了30分钟,但什么也没完成。
帮助表示感谢!