Hi there!
Im advancing into classes and for a project, I need to prepare a structure that is most effective to be a list of objects that have previously defined own variables, methods, etc. The idea is to USE those methods with different vars at each element off the list thus saving coding efforts, ok?
To illustrate this, I have prepared a simplified classes that relate the same way as my more-complicated classes. As I mentioned, I have a class of objects, then I prepare another class which is basically a list container with elements of the first one… Then I’d like to use N objects of the first type and refer to them by index of the list. Here is my testing code:
class Numbers():
def __init__(self):
self.a = 0
self.b = 0
def SetValues(self,new_a,new_b):
self.a,self.b = new_a,new_b
def PrintSumValues(self):
print self.a + self.b
class List_of_Numbers():
L_of_Numbers = [] # list of objects of type "Numbers"
data = {0:[1,8],1:[2,3],2:[4,3],3:[5,1]}
def __init__(self):
NewNumbers = Numbers()
for i in range(len(self.data)):
j = self.data.keys()[i]
new_a = self.data[j][0]
new_b = self.data[j][1]
NewNumbers.SetValues(new_a,new_b)
self.L_of_Numbers.append(NewNumbers)
def PrintAll(self):
for i in range(len(self.L_of_Numbers)):
someNumbers = self.L_of_Numbers[i]
someNumbers.PrintSumValues()
print
In the List_of_Numbers() class, there is a data variable (constant in the above example) which contains the data to instantiate the other object, elements of the list. This may be an external source of data - it is not important…
Then somewhere in my code I have:
List_of_Nums = List_of_Numbers()
.............................................
.............................................
.............................................
List_of_Nums.PrintAll()
resulting to printing ALL sums of elements in the list.
The problem is that the printing is incorrect! My results are:
6
6
6
6
rather then:
9
5
7
6
Which means to me that in the whole list only the last values are available at each element of the list…
Any ideas on how to correct the situation and obtain a list with the correct content???
Regards,