m*****e 发帖数: 35 | 1 lass M(object):
def __init__ (self):
self.a=20
a=[M()] *10
print len(a)
for phc in (a):
print "[%d]"%phc.a
a[0].a=30
for phc in (a):
print "[%d]"%phc.a
============
I want to have an array of M object. but it seems that everytime I change a
value in a[0], all other elements are changed too? what is wrong? how to
correct it?
thank you |
m******e 发帖数: 44 | 2 All elements in a refer to the same object or address, change:
a=[M()] *10
to
a=[M() for i in range(10)]
【在 m*****e 的大作中提到】 : lass M(object): : def __init__ (self): : self.a=20 : a=[M()] *10 : print len(a) : for phc in (a): : print "[%d]"%phc.a : a[0].a=30 : for phc in (a): : print "[%d]"%phc.a
|
m*****e 发帖数: 35 | 3
【在 m******e 的大作中提到】 : All elements in a refer to the same object or address, change: : a=[M()] *10 : to : a=[M() for i in range(10)]
|