problems creating and adding class instances to a list:

R

Robert Somerville

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.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.y[1]


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

rsomerville@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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top