[英]Scope of lists in Python 3
This may be a very stupid question, but I'm a little uncertain as to why lists behave differently to other variables in Python 3, with regard to scope. 这可能是一个非常愚蠢的问题,但我有点不确定为什么列表在范围方面与Python 3中的其他变量的行为不同。 In the following code...
在以下代码中......
foo = 1
bar = [1,2,3,4]
def baz():
foo += 1
bar[0]+=1
I understand why foo += 1
throws an error with regard to foo
being outside of local scope. 我理解为什么
foo += 1
会引发关于foo
超出局部范围的错误。 Why doesn't bar[0]+=1
throw the same error though? 为什么
bar[0]+=1
不会抛出相同的错误?
The variable foo
points to an object (an integer). 变量
foo
指向一个对象(一个整数)。 The variable baz
points to an object (a list). 变量
baz
指向一个对象(一个列表)。 If you try and reassign baz
to another object you would get the error. 如果您尝试将
baz
重新分配给另一个对象,则会出现错误。 But you're not, you're just calling a method on the list object, and anyone can do that. 但你不是,你只是在列表对象上调用一个方法,任何人都可以这样做。
In python, you can't modify globals without the 'global' keyword. 在python中,如果没有'global'关键字,则无法修改全局变量。 This is for clarity.
这是为了清楚起见。
foo=1
def bar():
global foo
foo=2
bar()
#foo is now 2!
Since bar[0]+=foo modifies the an element of a list, not the value of the list variable itself, it is legal. 由于bar [0] + = foo修改了列表的元素,而不是列表变量本身的值,因此它是合法的。
When you execute the code, you will get 当你执行代码时,你会得到
....
foo += 1
UnboundLocalError: local variable 'foo' referenced before assignment
foo += 1
is actually evaluated like this. foo += 1
实际上是这样评估的。 foo = foo + 1
. foo = foo + 1
。 So, you are adding 1
to the value of foo
and storing it in a variable foo
. 因此,您将
foo
的值加1
并将其存储在变量foo
。 Since there is an assignment happening, Python assumes that foo
is a local variable. 由于发生了赋值,Python假定
foo
是局部变量。 But, if it is a local variable, in the expression foo + 1
, what would be the value of foo
? 但是,如果它是局部变量,在表达式
foo + 1
, foo
的值是多少? Python couldn't answer this question. Python无法回答这个问题。 That is why it throws that error.
这就是它抛出错误的原因。
But, when you do bar[0] += 1
, Python evaluates it like this bar[0] = bar[0] + 1
. 但是,当你执行
bar[0] += 1
,Python会像这个bar[0] = bar[0] + 1
一样评估它。 Since, it already knows what bar
is, and you are just trying to replace the first element in it, it allows it. 因为它已经知道了什么是
bar
,你只是想要替换它中的第一个元素,它允许它。 In the last case, we were creating a new local variable called foo
by doing foo += 1
, but here, we are just altering the same object. 在最后一种情况下,我们通过执行
foo += 1
来创建一个名为foo
的新局部变量,但在这里,我们只是改变了同一个对象。 So Python allows this. 所以Python允许这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.