Python中global用法详解 |
您所在的位置:网站首页 › python函数global的用意 › Python中global用法详解 |
1. 文档说明 在python3.3.2的官方api帮助文档上看到, 如下一段话: 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. Names listed in a global statement must not be used in the same code block textually preceding that global statement. 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. 实例说明 def scope_test(): def do_local(): spam = "local spam" def do_nonlocal(): nonlocal spam spam = "nonlocal spam" def do_global(): global spam spam = "global spam" spam = "test spam" do_local() print("After local assignment:", spam) do_nonlocal() print("After nonlocal assignment:", spam) do_global() print("After global assignment:", spam) scope_test() print("In global scope:", spam) 备注:该实例代码来源于python3.3.2 官方文档。运行结果是:
可以看到,只有在与定义方法相平行的代码中输出全局变量的值。 def do_global(): global spam spam = "global spam"假设去掉global关键字,运行就会出如下结果:
总结: 全局变量的使用是为了使我们在一个类或一个函数中使用由函数返回的变量,并进行复杂的计算过程而使用。而对于一个函数的局部变量,则只在一个函数内部是可使用的,而如果需要跨越不同的函数或者类则需要在基础函数中返回一个该值,在下一个函数中运行其方法才能获取该值进行计算,如果程序不复杂在一个类中可以解决。全局变量会为我们节省不少的时间,以及内存空间。
其他网友对global的用法介绍:http://blog.csdn.net/nilxin/article/details/1523898
|
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |