I need to represent some data as a hierarchy where an object can have one parent and many children. I also need to be able to get a child’s parent in the same way that i would a child.
I tried this
class Root():
def __init__(self):
self.child = Node(self)
class Node():
def __init__(self, parent):
self.parent = parent
Is there a common way of solving this problem out there
I think that this is basically how
Tkinterdoes it:Now,
Rootknows all it’s children via thechildrenattribute, and the children know their parents via theparentattribute.Of course, you could make things a little more interesting by giving
Nodeobjects achildrenattribute as well — ThenNodes can parent moreNodes. Neat.There are some downsides here (mainly cyclic references). If you want to avoid that, you could use
weakref.refs to store the references to the children/parents, but I’ll defer that to another question if necessary.