pythonclassinstance-variablesclass-attributesrenewal

How to update a class attribute when an instance attribute changes?


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?


Solution

  • If you want modifications made to an instance attribute to effect the value of a class attribute, you can make the instance attribute a property and place the additional logics in its setter method instead:

    class Test:
        W = 0
    
        def __init__(self, l, A):
            self.l = l
            self.A = A
    
        @property
        def A(self):
            try:
                return self._A
            except AttributeError:
                return 0
    
        @A.setter
        def A(self, value):
            Test.W += (value - self.A) * self.l
            self._A = value
    

    so that:

    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)
    

    outputs:

    149
    430
    

    Demo: https://ideone.com/pqUN4w