Search code examples
pythonparent-childparentchildren

How to link parent and children to each other?


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.

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)

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)

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.

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().

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!


Solution

  • 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.