I’m trying to create a list of objects (Elements), where each element contains a list of objects (GaussPoints). The number of GaussPoints per Element can be variable, although in the example below each element has only one GaussPoint for simplicity.
class Element:
gp = []
class GaussPoint:
argument = 0
k = 0
elements = []
for ele in xrange(4):
k = k+1
anEle = Element()
aGP = GaussPoint()
aGP.argument = k
print k
elements.append(anEle)
elements[ele].gp.append(aGP)
print "testing the data structure:"
for ele in xrange(4):
print elements[ele].gp[0].argument
The output is:
1
2
3
4
testing the data structure:
1
1
1
1
What I’m expecting would be:
1
2
3
4
testing the data structure:
1
2
3
4
Somehow the code doesn’t create a new list of GaussPoints for each Element, but appends to the same one.
I’m obviously misunderstanding something quite fundamental about Python. Could anyone please help?
You need to make
Element.gpan instance variable, like so:Currently,
gpis a member of the class itself and is in effect shared by all instances of the class. You change it in one, and it appears to change in all.It is arguably good style to make the same change to
GaussPoint.argument:Finally, I’d recommend reading the tutorial on classes.