very strange problem in 2.4

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Sat Apr 8 13:53:50 EDT 2006


conor.robinson at gmail.com a écrit :
> The Problem (very basic, but strange):
> 
> I have a list holding a population of objects, each object has 5 vars
> and appropriate funtions to get or modify the vars. 

Which are probably not necessary:
http://dirtsimple.org/2004/12/python-is-not-java.html

(in short: Python as a mechanism named "properties" that allow you to 
"gateway" attribute access thru hiddens getter and setter).

> When objects in
> the list have identical vars (like all = 5 for var "a" and all = 10 for
> var "b" across all vars and objects) and i change
> 
> self.mylist[i].change_var_a(5)
> 
> to a new value, in this case var "a" in object i to 5, now all vars of
> type "a" in all objects in my list are changed to 5 instead of just var
> "a" in object mylist[i], which is my goal.

(snip)
> 
> What is python doing? Am I missing something? Any ideas at all would be
> wonderful?
> 

It would have helped if you had posted your code. Anyway, at least two 
things could lead to the behaviour you describe:

1/ you have class attributes instead of instance attributes, ie:

class MyClass(object):
   # this attribute belongs to the class
   class_attrib = 42

   def __init__(self, instance_attrib):
     # this attribute belongs to the instance
     self.instance_attrib = instance_attrib

2/ you in fact have in your list multiple references to the same instance.

My 2 cents



More information about the Python-list mailing list