Python中global用法详解

1. 文档说明

   在python3.3.2的官方api帮助文档上看到, 如下一段话:

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  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. 实例说明

[python]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. def scope_test():  
  2.     def do_local():  
  3.         spam = "local spam"  
  4.     def do_nonlocal():  
  5.         nonlocal spam  
  6.         spam = "nonlocal spam"  
  7.     def do_global():  
  8.         global spam  
  9.         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 官方文档。

运行结果是:


可以看到,只有在与定义方法相平行的代码中输出全局变量的值。

[python]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. def do_global():  
  2.     global spam  
  3.     spam = "global spam"  
假设去掉global关键字,运行就会出如下结果:


意思说 span没有被定义。

总结:

全局变量的使用是为了使我们在一个类或一个函数中使用由函数返回的变量,并进行复杂的计算过程而使用。而对于一个函数的局部变量,则只在一个函数内部是可使用的,而如果需要跨越不同的函数或者类则需要在基础函数中返回一个该值,在下一个函数中运行其方法才能获取该值进行计算,如果程序不复杂在一个类中可以解决。全局变量会为我们节省不少的时间,以及内存空间。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值