How do I recalculate the value of a variable every time it is used?
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 to share