Python中全局变量与局部变量错误
2017-12-19 16:06
197 查看
Why am I getting an UnboundLocalError when the variable has a value?
It can be a surprise to get the UnboundLocalError in previously working code when it is modified by adding an assignment statement somewhere in the body of a function.This code:
>>> x = 10 >>> def bar(): ... print x >>> bar() 10
works, but this code:
>>> x = 10 >>> def foo(): ... print x ... x += 1
results in an UnboundLocalError:
>>> foo() Traceback (most recent call last): ... UnboundLocalError: local variable 'x' referenced before assignment
This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope. Since the last statement in foo assigns a new value to x,
the compiler recognizes it as a local variable. Consequently when the earlier print x attempts to print the uninitialized
local variable and an error results.
In the example above you can access the outer scope variable by declaring it global:
>>> x = 10 >>> def foobar(): ... global x ... print x ... x += 1 >>> foobar() 10
This explicit declaration is required in order to remind you that (unlike the superficially analogous situation with class and instance variables) you are actually modifying the value of the variable in the outer scope:
>>> print x 11
相关文章推荐
- python unittest TestCase间共享数据(全局变量的使用)
- 多线程-共享全局变量(python版)
- 3.8 Python函数中的局部变量和全局变量
- Python 语言及其应用 Chapter_4_Note_5 全局变量和局部变量
- Python新手学习基础之函数-全局变量和局部变量
- java和python改变全局变量的对比
- python中的多线程-共享全局变量
- openstack中的配置文件和python中的全局变量
- python全局变量
- Python module中的全局变量
- python的全局变量应用
- python基础 - global关键字及全局变量的用法
- python 经验: from x import * 影响全局变量使用
- python第十篇之-全局变量
- 浅析Python中的Python全局变量
- python全局变量
- python返回值与局部全局变量
- Python全局变量和局部变量
- 转:Python之全局变量
- 浅析Python中的Python全局变量