我不明白为什么当我更改 x 时变量“y”不更新? (“y”变量依赖于“x”,对吧?)
x = 5
y = x*2
print(x)
print(y)
x = 3
# Expect it to print '3' and '6' instead it print '3' and '10'
print(x)
print(y)
(“y”变量依赖于“x”,对吗?
No.
Few programming languages have dependent / computed variables[0] and Python is not one of them[1]. When y = x*2
is executed, the expression on the right-side of the =
is fully evaluated and the result set as the value of y
. y
is thereafter independent from x
[2].
一般来说,如果你想要y
是一个函数x
...您将其定义为函数x
:
x = 5
def y(): return x*2
print(x)
print(y())
x = 3
# Expect it to print '3' and '6' instead it print '3' and '10'
print(x)
print(y())
- 我知道
make
的惰性变量和 Perl 的绑定标量
- 它确实计算了属性(又名属性)但这是一个非常不同的事情
- 有些情况看起来有点像因变量,例如如果你设置
y
到一个可变的子结构x
对此子部分的更改x
将通过可见y
。但这实际上并不是依赖关系,只是两个变量指向相同的(可变)结构,因此两个变量都“看到”应用于该共享结构的突变。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)