Reputation: 8367
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
Upvotes: 0
Views: 775
Reputation: 310049
I think that this is basically how Tkinter
does it:
class Root(object):
def __init__(self):
self.children = []
class Node(object):
def __init__(self,parent):
self.parent = parent
parent.children.append(self)
Now, Root
knows all it's children via the children
attribute, and the children know their parents via the parent
attribute.
r = Root()
n = Node(r)
r.children[0] is n #True
n.parent is r #True
Of course, you could make things a little more interesting by giving Node
objects a children
attribute as well -- Then Node
s can parent more Node
s. Neat.
There are some downsides here (mainly cyclic references). If you want to avoid that, you could use weakref.ref
s to store the references to the children/parents, but I'll defer that to another question if necessary.
Upvotes: 8