How do I recalculate the value of a variable every time it is used?

I want the variable to be calculated every time it is used. For example, var1 = var2 + var3

it var1

is printed every time . How do I create a dynamic variable?

var2 = 4
var3 = 2
print(var1)  # 6
var3 = 8
print(var1)  # 12

      

+3


source to share


2 answers


You will need an instance property of the class. The property will execute some code each time it is accessed. For example, here's a property that increments its value each time it is accessed. Define __str__

to access the property, so you can print(var1)

and get its incremental value.

class MyVar(object):
    def __init__(self, initial=0):
        self._var1 = initial

    @property
    def var1(self):
        self._var1 += 1
        return self._var1

    def __str__(self):
        return str(self.var1)

var1 = MyVar()
print(var1)  # 1
print(var1)  # 2
print(var1.var1)  # 3

      



Calculate var1 = var2 + var3

:

class MyVar(object):
    def __init__(self, var2, var3):
        self.var2 = var2
        self.var3 = var3

    @property
    def var1(self):
        return self.var2 + self.var3

var = MyVar(4, 2)
print(var.var1)  # 6
var.var3 = 8
print(var.var1)  # 12

      

+10


source


You can also store the calculation function in a variable and call

whenever you need a value:



>>> var1 = lambda: var2 + var3
>>> var2 = 4
>>> var3 = 2
>>> print(var1())
6
>>> var3 = 8
>>> print(var1())
12

      

+2


source







All Articles