为什么在更改其因变量后不更新变量? [英] Why is a variable not updating after changing its dependent variable?

查看:63
本文介绍了为什么在更改其因变量后不更新变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么更改x时变量'y'不会更新?("y"变量取决于"x"吗?)

I don't understand why the variable 'y' doesn't update when I change the x? (The 'y' variable is dependent on 'x' right?)

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"对吗?

(The 'y' variable is dependent on 'x' right?

不.

很少有编程语言具有因变量/计算出的变量 [0],而Python并不是其中之一[1].当执行 y = x * 2 时,将完全评估 = 右侧的表达式并将结果集设置为 y .此后, y 独立于 x [2].

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 的函数:

Generally speaking, if you want y to be a function of x... you define it as a function of 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())

[0]我知道 make 的惰性变量和Perl的束缚标量

[0] I know of make's lazy variables and Perl's tied scalars

[1]它确实已经计算了属性(又称属性),但这是完全不同的事情

[1] it does have computed attributes (aka properties) but that's a very different thing

[2]有些情况看起来像因变量,例如如果将 y 设置为 x 的可变子结构,则对 x 的此子部分的更改将通过 y .不过,这实际上并不是依赖关系,只是两个变量指向相同的(可变)结构,因此这两个可见"突变都应用于该共享结构.

[2] There are situations which kind-of look like dependent variables e.g. if you set y to a mutable sub-structure of x changes to this sub-part of x will be visible through y. That's not actually a dependency though, it's just that the two variables point to the same (mutable) structure, so both "see" mutations applied to that shared structure.

这篇关于为什么在更改其因变量后不更新变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆