python - 全局变量 : assignment vs method call

标签 python python-3.x scope namespaces

<分区>

为避免意外修改全局变量,python 在分配给全局变量之前需要显式的 global 语句。但是,无需任何额外语句即可通过调用其方法来修改全局变量:

x = [1, 2]
y = [1, 2]
def f():
  global x
  x = x + [3] # won't affect global variable without global statement
  y.append(3) # will affect global variable without global statement

这似乎有点不一致。之所以做出这种设计选择,是因为与用一个全新的对象替换它们相比,通过方法调用修改全局可变对象被认为危险性较小/不好吗?如果是,为什么?

最佳答案

来自documentation :

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.

在您的情况下,y 在函数内部被引用,因此隐式是全局的。另一方面,x 被分配了一个值,因此它必须是本地的,除非另外明确声明。

文档进一步回答了您的问题:

Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you’d be using global all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.

关于python - 全局变量 : assignment vs method call,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39539391/

相关文章:

python - 如何在python中的循环外设置变量

python - python 中的多重处理 - 通过添加结果来节省内存

python - 如何使用用于创建子帧的相同 groupby 调用在数据帧的子帧上应用 groupby

python-3.x - 无法连接到docker容器内的postgres数据库

python - 从文件读取时一次性跳过所有空间

javascript - 过滤$范围错误: Unknown provider: $scopeProvider <- $scope <- transformSensorStatusFilter

python - wtform 上的实时验证。我可以访问前端的验证器吗?

python - 从过滤器返回第一个元素或无

c++ - "Entities with the same name defined in an outer scope are hidden"不成立

c# - 为什么我不能在 C# 中的不同作用域中声明同名变量?