在 Python 中,如果您想更改变量的值,有多种方法:
foo = 1 # By assignment
bar.func() # By calling its method.
for baz in range(5): # By "leaking" from a loop
出于好奇,我想在“正常”程序中找到实现此目标的所有方法。我所说的“正常”是指不直接操纵locals()
或者做类似的事情。
我也知道有一些关于 Python 是否有真正的“变量”的讨论,但我们在这个问题上不要关注这一点。
最佳答案
恐怕您真的不清楚“更改变量的值”意味着什么。 Python 对象具有状态,因此您可以连贯地询问哪些方法可能会改变对象的状态,并且 Python 中的名称可以绑定(bind)到对象,因此您可以连贯地询问此类绑定(bind)如何更改。
对于前者,取决于对象的类型。对于后者,请参阅 Python 语言引用手册中的第 4.2.1 节(“名称绑定(bind)”):
The following constructs bind names: formal parameters to functions,
import
statements, class and function definitions (these bind the class or function name in the defining block), and targets that are identifiers if occurring in an assignment,for
loop header, or afteras
in awith
statement orexcept
clause. Theimport
statement of the formfrom ... import *
binds all names defined in the imported module, except those beginning with an underscore. This form may only be used at the module level.A target occurring in a
del
statement is also considered bound for this purpose (though the actual semantics are to unbind the name).
关于python - 有多少种方法可以改变变量的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53122579/