为避免意外修改全局变量,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.