attribute assignment effects all class instances

Jeffrey Froman jeffrey at fro.man
Thu Sep 9 20:21:14 EDT 2004


anon wrote:

> 
> Here's the wierd thing, in another module I have:
> 
> node.adjacent[left] = y
> 
> where node is an instance of the Node class.  This statement assigns
> all Node instances the value y to attribute adjacent[left].  This seems
> very wrong, unless python resolves names in a case-insensitive way.

When you assign the default value for adjacent in the constructor definition
as you do, that list is created only one time, and the same list is passed
as the default value for each instance of Node.

Thus, when you alter the list, the change shows up in all instances, because
they are all using the same list.

> When I try the alternate:
> 
> node.adjacent = [None, y, None, None]
> 
> I get the behavior I expect (ie. only the instance node gets its
> attribute set)

In the second case you have not altered the existing list, but rather
reassigned your attribute to a new list. Hence, only the node you are
working on changes. At that point all of the nodes *except* the one you
just changed are using the same list for the "adjacent" attribute.
 

Hope that helps,
Jeffrey



More information about the Python-list mailing list