0

I have two classes Test_1 and Test_2 where test_2 includes the method setValues.

class Test_1():

    def __init__(self):
        self.dim = float
        self.list = Test_2()


    def init(self, dim, valuesT, valuesW):
        self.dim = dim
        self.list = [Test_2()] * dim


        for i in range(self.dim):
            self.list[i].setValues(mean[i], valuesT[i], valuesW[i])


class Test_2():

    def __init__(self):

        self.mean = float
        self.T = float
        self.W = float
        
    def setValues(self, mean, T, W): 

        self.mean = mean
        self.T = abs(mean - T) 
        self.W = abs(W - mean) 

When I create an instance of Test_1 and call the init method of this class passing the params (3,[1,2,3],[3,4,5], [6,7,8]) I am expecting the creation of 3 instances of Test_2 class and for the T and W values to be initialised in the list objects. However this is not the case and the T and W values seem to be overwritten for all 3 Test_2 objects to the latest T and W values. The below code produces the values:

1 3 6

6 6 6

    for i in range(self.dim):
        self.list[i].setValues(mean[i], T[i], W[i])
        print("List while in loop: ", self.list[i].mean)

    for i in range(self.dim):
        print("List after loop: ", self.list[i].mean)

Could anyone help shed some light on why this may be? I'm fairly new to OOP.

Lauren
  • 61
  • 6
  • 2
    `[Test_2()] * dim` creates a list with `dim` references to the *same `Test_2()` object*. You can use something like `[Test_2() for _ in range(dim)]` instead – juanpa.arrivillaga Oct 02 '20 at 09:00
  • 2
    While unrelated to your question, you're missunderstanding `__init__`: You're assigning types, but that isn't really a thing in python. – syntonym Oct 02 '20 at 09:01
  • @juanpa.arrivillaga Hey, thanks for the reply! Should this matter if I'm trying to index into the list of objects to modify the values within each? ie ```self.list[0].setValues``` should act upon the first ```Test_2()``` object in the list and so on?? – Lauren Oct 02 '20 at 09:22
  • 1
    @Lauren *there is only one object*. It is referenced `dim` number of times. Read the linked duplicate at the top – juanpa.arrivillaga Oct 02 '20 at 09:31
  • @juanpa.arrivillaga got it, thanks for the lesson! – Lauren Oct 02 '20 at 09:39
  • @Lauren so, consider, `data = [object()]*3` then `for obj in data: print(id(obj))` – juanpa.arrivillaga Oct 02 '20 at 09:48

0 Answers0