Unable to modify a global int, but can modify a list. How?

前端 未结 2 1357
醉酒成梦
醉酒成梦 2021-01-13 19:22

LISTL = [] VAR1 = 0 def foo(): ... VAR1 += 1 ... return VAR1 ...

相关标签:
2条回答
  • 2021-01-13 20:02

    If you assign to a variable within a function, that variable is assumed to be local unless you declare it global.

    0 讨论(0)
  • 2021-01-13 20:16

    The reason for this difference has to do with how Python namespaces the names. If you're inside a function definition (def foo():), and you ACCESS a name (VAR1 or LISTL), it will first search your local namespace, where it will find nothing, and then it will search the namespace of the module the function was defined in, all the way up to the global namespace until it finds a match, or fails.

    However, ACCESSING a name, and ASSIGNING a name, are two different concepts. If you're again within your function definition, and you say VAR1 = 2, you're declaring a new variable with the new local name VAR1 inside the function. This makes sense if you consider that otherwise you would encounter all sorts of naming collisions if there was no such namespacing at work.

    When you append to a list, you are merely ACCESSING the list, and then calling a method on it which happens to change its conceptual value. When you use do +=, you're actually ASSIGNING a value to a name.

    If you would like to be able to assign values to names defined outside of the current namespace, you can use the global keyword. In that case, within your function, you would first say global VAR1, and from there the name VAR1 would be the name in the outer namespace, and any assignments to it would take effect outside of the function.

    0 讨论(0)
提交回复
热议问题