Need help with simple OOP Python question

Peter Otten __peter__ at web.de
Mon Sep 5 16:43:02 CEST 2011


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.




More information about the Python-list mailing list