Use of Python global variables

Source: Internet
Author: User

If you want to assign a value to a global variable in a function, you must use the global statement.
 
   
  
  1. global VarName的表达式会告诉Python, VarName是一个全局变量,这样Python就不会在局部命名空间里寻找这个变量了。

  
 
  1. globals()和locals()函数
  2. 根据调用地方的不同,globals()和locals()函数可被用来返回全局和局部命名空间里的名字。
  3. 如果在函数内部调用locals(),返回的是所有能在该函数里访问的命名。
  4. 如果在函数内部调用globals(),返回的是所有在该函数里能访问的全局名字。
  5. 两个函数的返回类型都是字典。所以名字们能用keys()函数摘取。


 
   
  
  1. reload()函数
  2. 当一个模块被导入到一个脚本,模块顶层部分的代码只会被执行一次。
  3. 因此,如果你想重新执行模块里顶层部分的代码,可以用reload()函数。该函数会重新导入之前导入过的模块。语法如下:

 
   
  
  1. reload(module_name)

 
   
  
  1. 在这里,module_name要直接放模块的名字,而不是一个字符串形式。比如想重载hello模块,如下:
  2. reload(hello)
http://seniorzhai.github.io/2014/10/13/Python-%E5%8D%81---%e5%b8%b8%e7%94%a8%e5%86%85%e5%bb%ba%e6%a8%a1%e5%9d%97/


From for notes (Wiz)

Use of Python global variables

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.