attribute assignment effects all class instances

Andrew Durdin adurdin at gmail.com
Fri Sep 10 00:31:23 EDT 2004


On Thu, 09 Sep 2004 19:14:20 -0700, Jeff Shannon <jeff at ccvcorp.com> wrote:
> And since others have already told you *why* you're having a problem,
> I'll limit myself to showing you one possible way around that problem.

And for another way around: just change the line in __init__ from
    self.adjacent = adjacent
To
    self.adjacent = list(adjacent)

This will alter the overall behaviour -- the new node will always make
a copy of the list. An example is best to show the difference. Suppose
you have the following code:

adj = [node1, node2, node3, node4]
newnode1 = node(adjacent=adj)
newnode2 = node(adjacent=adj)
...  # Some other irrelevant code
newnode2.adjacent[left] = node5

With Jeff's solution (and your original), newnode1.adjacent will also
have changed, so will be [node1, node5, node3, node4]. With the
solution above which copies the list, newnode1 will not have changed.

The solution you should use depends on what behaviour you want for
this situation.



More information about the Python-list mailing list