With lambda function
You can create a lambda function. But, it requires you to add empty parenthesis after each call of b
.
>>> a = 50
>>> b = lambda: a * 3
>>> b
<function <lambda> at 0xffedb304>
>>> b()
150
>>> a = 45
>>> b()
135
EDIT: I have already respond at this kind of anwser here: How to create recalculating variables in Python
With a homemade class
Another way given on this same thread is to create an Expression
class, and change the repr
return.
Fair warning: this is a hack only suitable for experimentation and play in a Python interpreter environment. Do not feed untrusted input into this code.
class Expression(object):
def __init__(self, expression):
self.expression = expression
def __repr__(self):
return repr(eval(self.expression))
def __str__(self):
return str(eval(self.expression))
>>> a = 5
>>> b = Expression('a + 5')
>>> b
10
>>> a = 20
>>> b
25