1. 文档说明
在python3.3.2的官方api帮助文档上看到, 如下一段话:
1.
The global statement is a declaration which holds
for
the entire current code block. It means that the listed identifiers are to be interpreted as globals. It would be impossible to assign to a global variable without global, although free variables may refer to globals without being declared global.
2.
Names listed in a global statement must not be used in the same code block textually preceding that global statement.
3.
Names listed in a global statement must not be defined as formal parameters or in a
for
loop control target,
class
definition, function definition, or
import
statement.
翻译成中文大概意思是:global语句是适用于当前整个代码块的声明。它是全局变量的标识符。如果某名字在局部名字空间中没有定义, 就自动使用相应的全局名字. 没有global是不可能手动指定一个名字是全局的.在 global 中出现的名字不能在global 之前的代码中使用.在 global 中出现的名字不能作为形参, 不能作为循环的控制对象, 不能在类定义, 函数定义, import语句中出现.
与nonlocal关键字的区别:
global语句用以知名某个特定的变量为全局作用域,并重新绑定它。nonlocal语句用以指明某个特定的变量为封闭作用域,并重新绑定它。
2. 实例说明
01.
def scope_test():
02.
def do_local():
03.
spam =
"local spam"
04.
def do_nonlocal():
05.
nonlocal spam
06.
spam =
"nonlocal spam"
07.
def do_global():
08.
global spam
09.
spam =
"global spam"
10.
11.
spam =
"test spam"
12.
do_local()
13.
print(
"After local assignment:"
, spam)
14.
do_nonlocal()
15.
print(
"After nonlocal assignment:"
, spam)
16.
do_global()
17.
print(
"After global assignment:"
, spam)
18.
19.
scope_test()
20.
print(
"In global scope:"
, spam)
备注:该实例代码来源于python3.3.2 官方文档。运行结果是:
可以看到,只有在与定义方法相平行的代码中输出全局变量的值。
1.
def do_global():
2.
global spam
3.
spam =
"global spam"
假设去掉global关键字,运行就会出如下结果:
意思说 span没有被定义。总结:
全局变量的使用是为了使我们在一个类或一个函数中使用由函数返回的变量,并进行复杂的计算过程而使用。而对于一个函数的局部变量,则只在一个函数内 部是可使用的,而如果需要跨越不同的函数或者类则需要在基础函数中返回一个该值,在下一个函数中运行其方法才能获取该值进行计算,如果程序不复杂在一个类 中可以解决。全局变量会为我们节省不少的时间,以及内存空间。
其他网友对global的用法介绍:http://blog.csdn.net/nilxin/article/details/1523898
转载于:https://my.oschina.net/airship/blog/669627