简体   繁体   中英

How to make a variable interactively dependent to its assigned formula

In the code below:

>>> a=10
>>> b=10
>>> c=10
>>> D=a+b+c
>>> D
30
>>> a=5
>>> D
30

I understand that D was assigned a value in row 4 and therefore it will hold that value unless changed explicitly (eg D=33 ). But I would like to have an interactive D that would change when a, b, or c changes. How would we approach this issue?

a=10
b=10
c=10

def D():
    return a+b+c

print D()

a=1

print D()

The most simple solution I can think of is by a class. Here is an example that fits your question although it is not very general:

class InteractiveSumOf3Variables(object):

    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

    def get_value(self):
        return self.a+self.b+self.c



D = InteractiveSumOf3Variables(10,10,10)

print D.get_value()
>>> 30

D.a = 5

print D.get_value()
>>> 25

You can either use a generator or a function in either as a named (as suggested by the previous answers) or as an anonymous lambda

>>> from itertools import count
>>> foo_D = lambda : a + b + c #Lambda
>>> gen_D = (a+b+c for _ in count()) #generator expression
>>> a = 1
>>> b = 2
>>> c = 3
>>> next(gen_D)
6
>>> c = 4
>>> next(gen_D)
7
>>> foo_D()
7
>>> c = 3
>>> foo_D()
6 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM