In Python, why do I get an 'undefined local variable' error for counters but not for lists?
If I alter a variable declared at the top of the file/module from within a method (no classes involved), it only works in the case of lists/containers, but not if my variable was a simple counter. See the following code for example:
counter = 0
counterList = []
def incrementCounter():
counter += 1
def addToList():
counterList.append(1)
# works:
addToList()
# doesn't work:
incrementCounter()
print counterLi开发者_如何学运维st, counter
What is the reason for this differing behaviour?
Try
def incrementCounter():
global counter
counter += 1
The assignment to counter
inside incrementCounter()
otherwise implicitely makes counter
local to that function.
The line counter += 1
does not actually change the integer object counter
points to -- integers are immutable in Python. The line is rather equivalent to
counter = counter + 1
thus creating a new integer object and making the name counter
point to that new integer object. When compiling the function, Python detects the assignment to counter
and assumes the name counter
to be local to the function even before the assignment. When the above line gets executed, the right hand side is evaluated. Python tries to look up the name counter
in the local namespace, since it assumes counter
to be local. There is no such name in the local namespace though, hence the error message.
The actual reason is that you are not changing the value of the list by appending to it. If you increment counter, you are changing the value, which is not allowed, unless you declare it as global
.
精彩评论