From: Robert Somerville on
I am trying to create a list of consisting of multiple instances of the
same class, The Problems i am having is that i seem to be accessing the
same memory.. How should i solve this Python problem ?

Here is some sample code demonstraing my problem (same memory) :
from copy import copy as cp

class ctest():
x = int
y = [1,2,3]


def return_class(i):
d = ctest()
d.y[1] = i*10
return (d)

if __name__ == '__main__':
c_list= []
print 'len-a =',len(c_list)
for i in range(5):
e = cp(return_class(i))
c_list.append(e)
print 'i= ',i,c_list[i].y[1]
if ( i > 0):
print 'i-1= ',i-1,c_list[i-1].y[1]

print 'len = ' , len(c_list)
for i in range(5):
print 'i= ',i,c_list[i].y[1]


here is the output demonstrating that i am addressing the same memory:

rsomerville(a)galena:~/workspace/CSIRO_gui/trunk/src$ python test4.py
len-a = 1
i= 0 0
i= 1 10
i-1= 0 10
i= 2 20
i-1= 1 20
i= 3 30
i-1= 2 30
i= 4 40
i-1= 3 40
len = 6
i= 0 40
i= 1 40
i= 2 40
i= 3 40
i= 4 40

From: Chris Rebert on
On Mon, Apr 19, 2010 at 2:29 PM, Xavier Ho <contact(a)xavierho.com> wrote:
> On Tue, Apr 20, 2010 at 7:21 AM, Robert Somerville
> <rsomerville(a)sjgeophysics.com> wrote:
>>
>> class ctest():
>>   x = int
>>   y = [1,2,3]
>
> Variables defined directly under the class are known as "static variables"
> in many other languages. Here in Python it's called a class variable, but
> they're still the same concept.
>
> What you want is "instance variables", which are not shared by the class
> instances, but different depending on each instance instead. That said,
>
> class ctest():
>     def __init__(self):
>         self.x = int

Additionally, `self.x = int` might not do what you thought it does. It
does *not* create a new instance variable of type 'int'. Instead, it
literally assigns to a new instance variable x the *function*† that
converts values into integers.

Cheers,
Chris
--
† This isn't entirely accurate; I'm oversimplifying for ease of understanding.
http://blog.rebertia.com
From: Chris Rebert on
On Mon, Apr 19, 2010 at 3:41 PM, Xavier Ho <contact(a)xavierho.com> wrote:
> On Tue, Apr 20, 2010 at 7:38 AM, Chris Rebert <clp2(a)rebertia.com> wrote:
>> Additionally, `self.x = int` might not do what you thought it does. It
>> does *not* create a new instance variable of type 'int'. Instead, it
>> literally assigns to a new instance variable x the *function*† that
>> converts values into integers.
>
> Thanks, Chris. I'm well aware of that. =]

It was obviously directed at the OP. :-)

Cheers,
Chris