我想要的是这个:
>>> x = 2
>>> y = x+10
>>> print(y)
12
>>> x = 30
>>> print(y) #Whatever x is, y is that number x, plus 10.
40
Run Code Online (Sandbox Code Playgroud)
如何在 Python 版本 x 中声明这种“因变量”?
我知道在标准库 Python 中执行此操作的唯一方法是使用属性,以便在每次访问属性时计算适当的值:
class Thing(object):
def __init__(self, x, y_add):
self.x = x
self.y_add = y_add
@property
def y(self):
return self.x + self.y_add
Run Code Online (Sandbox Code Playgroud)
正在使用:
>>> t = Thing(2, 10)
>>> t.x
2
>>> t.y
12
>>> t.x = 3
>>> t.y
13
Run Code Online (Sandbox Code Playgroud)
否则,您必须进行函数调用(y()而不是y)或使用类似sympy.