0

For example, if I say:

a = 50
b = 3 * a
a = 46

The value of b after this runs would still be 3 * 50 = 150. How would I assign b to equal 3 * a such that when a changes, the value of b also changes, without me having to restate b = 3 * a again?

EDIT: I would have searched this up but I really wasn't sure how to word it.

Aaron Hooper
  • 798
  • 2
  • 6
  • 14

3 Answers3

3

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
Community
  • 1
  • 1
Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97
1

Make b into a function:

def b():
    return 3 * a

then use it by calling it, i.e. b()

thebjorn
  • 26,297
  • 11
  • 96
  • 138
-1

What do you thing of this way ? :

class XB(object):
    def __getattribute__(self, name):
        try:
            return 3 * a
        except:
            return None


x = XB()

print 'x.b ==',x.b
a = 50
print 'x.b ==',x.b
a = 46
print 'x.b ==',x.b

return

x.b == None
x.b == 150
x.b == 138
eyquem
  • 26,771
  • 7
  • 38
  • 46