problems creating and adding class instances to a list:
Robert Somerville
rsomerville at sjgeophysics.com
Mon Apr 19 17:21:04 EDT 2010
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 at 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
More information about the Python-list
mailing list