I am working on optimization problems. As you know, optimization is an iterative process. Some sections are selected, and the weight of all sections is calculated.
I have code like this:
class Test:
W = 0
def __init__(self, l, A):
self.l = l
self.A = A
Test.W += self.A * self.l
instance1 = Test(5, 10)
instance2 = Test(3, 7)
instance3 = Test(6, 13)
print(Test.W)
instance1.A = 20
instance2.A = 30
instance3.A = 40
print(Test.W)
At creation of instances 1-3, the program calculated 149 for W. It is correct.
But if I change A values, the result is 149 again and again.
How can I update the class attribute W when I change A or l?
__init__code is not going to get rerun just because you changed an instance attribute. If you want to have side effects from setting an instance parameter, you should implement aTest.setA(new_A)method.a = 1,x = a,a = 3, thenprint(x)will print1not3. Assignment statements don't set up some on-going variable relationship. They get evaluated only when they are executed, and theTest.__init__()code only gets executed when the instances are being initialized.