1  Global

  The global statement and its nonlocal cousin are the only things that are remotely like declaration statements in Python. They are not type or size declarations; they are namespace declarations. The global statement tells Python that a function plans to change one or more global names.

  • Global names are variables assigned at the top level of the enclosing module file.
  • Global names must be declared only if they are assigned within a function.
  • Global names may be referenced within a function without being declared.

  In other words, global allows us to change names that live outside a def at the top level of a module file.

2  Example

  The global statement consists of the keyword global, followed by one or more names separated by commas.

X = 88                         # Global X

def func():
global X
X = 99 # Global X: outside def func()
print(X) # Prints 99

  

y, z = 1, 2                    # Global variables in module

def all_global():
global x # Declare globals assigned
x = y + z # No need to declare y, z: LEGB rule

  x, y, and z are all globals inside the function all_global. y and z are global because they aren’t assigned in the function; x is global because it was listed in a global statement to map it to the module’s scope explicitly. Without the global here, x would be considered local by virtue of the assignment.

3  Access globals

# thismod.py
var = 99 # Global variable == module attribute def local():
var = 0 # Change local var def glob1():
global var # Declare global (normal)
var += 1 # Change global var def glob2():
var = 0 # Change local var
import thismod # Import myself
thismod.var += 1 # Change global var def glob3():
var = 0 # Change local var
import sys # Import system table
glob = sys.modules['thismod'] # Get module object (or use __name__)
glob.var += 1 # Change global var def test():
print(var)
local();
print(var)
glob1();
print(var)
glob2();
print(var)
glob3()
print(var)

  run and get results

>>> import thismod
>>> thismod.test()
99
99
100
101
102

最新文章

  1. 全球IP分布表
  2. 【转】oracle数据库开发的一些经验积累
  3. 用LinkedList模拟栈数据结构的集合
  4. UnixBench测试
  5. 快速理解JS的闭包
  6. composer未升级报错
  7. 打开eclipse报错:发现了以元素 'd:skin' 开头的无效内容。此处不应含有子元素。
  8. python之lxml(xpath)
  9. scribe日志分析工具安装
  10. UISwitch swift
  11. 待验证的一些IOS问题
  12. 为GCD队列绑定NSObject类型上下文数据-利用__bridge_retained(transfer)转移内存管理权-备
  13. springmvc+maven
  14. Redis缓存项目应用架构设计一
  15. ansible字符串的处理
  16. HTML词法和语法
  17. 启动与关闭comcat服务器
  18. Linux 添加网卡
  19. js便签笔记(8)——js加载XML字符串或文件
  20. unity 加载读取外部XML

热门文章

  1. mongodb数据库的导出与导入
  2. 第四节:numpy之数组排序
  3. BZOJ 1452 Count 【模板】二维树状数组
  4. Maven学习总结(2)——Maven项目构建过程练习
  5. ZOJ 3199 Longest Repeated Substring
  6. GROOVY简单语法实习
  7. 洛谷 P3067 [USACO12OPEN]平衡的奶牛群Balanced Cow S…
  8. HDU 2665(主席树,无修改第k小)
  9. [AtCoder3954]Painting Machines
  10. 杂项:MIS(管理信息系统)