python - 有多少种方法可以改变变量的值?

标签 python variables

在 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 after as in a with statement or except clause. The import statement of the form from ... 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/

相关文章:

python - 线性回归 : Cost function working independently, 但不在 scipy.optimize 函数内

python - ChronoFresh SOAP 授权

python PIL 安装在共享主机上

php - 从 MySQL 查询填充组合框的值字段

javascript - 使用 javascript 将变量推送到现有函数

java - 用一个变量引用不同的类

python - 如何在 OpenCV 中获取图像的宽度和高度?

python - 刽子手 : File I/O strings and lists python

Javascript 类对象 - 相同值多个名称

java - 在字符串中使用@符号