Need help with simple OOP Python question

Jon Clements joncle at googlemail.com
Mon Sep 5 16:59:31 CEST 2011


On Sep 5, 3:43 pm, Peter Otten <__pete... at web.de> wrote:
> Kristofer Tengström wrote:
> > Thanks everyone, moving the declaration to the class's __init__ method
> > did the trick. Now there's just one little problem left. I'm trying to
> > create a list that holds the parents for each instance in the
> > hierarchy. This is what my code looks like now:
>
> > -----------------------------------------
>
> > class A:
> >     def __init__(self, parents=None):
> >         self.sub = dict()
> >         if parents:
>
> You should explicitly test for None here; otherwise in a call like
>
> ancestors = []
> a = A(anchestors)
>
> the list passed as an argument will not be used, which makes fore confusing
> behaviour.
>
> >             self.parents = parents
> >         else:
> >             self.parents = []
> >     def sub_add(self, cls):
> >         hierarchy = self.parents
> >         hierarchy.append(self)
>
> Here you are adding self to the parents (that should be called ancestors)
> and pass it on to cls(...). Then -- because it's non-empty -- it will be
> used by the child, too, and you end up with a single parents list.
>
> >         obj = cls(hierarchy)
> >         self.sub[obj.id] = obj
>
> While the minimal fix is to pass a copy
>
> def sub_add(self, cls):
>     obj = cls(self.parents + [self])
>     self.sub[obj.id] = obj
>
> I suggest that you modify your node class to keep track only of the direct
> parent instead of all ancestors. That makes the implementation more robust
> when you move a node to another parent.

I may not be understanding the OP correctly, but going by what you've
put here, I might be tempted to take this kind of stuff out of the
class's and using a graph library (such as networkx) - that way if
traversal is necessary, it might be a lot easier. But once again, I
must say I'm not 100% sure what the OP wants to achieve...

Jon.



More information about the Python-list mailing list