python 归纳 (六)_模块变量作用域

test_module2.py:

# -*- coding: utf-8 -*-
"""
测试 模块变量的作用域

总结:
1 其他模块的变量,在当前模块的任何地方,包括函数都可以通过 模块.变量 访问,包括读写
2 本模块的变量, 在函数中访问时,第一次出现是读操作,直接使用 第一次出现是写操作,必须gloabl 声明 否则变成局部变量
3 在本模块头部引用外部模块变量,所有函数都能访问。 如果只在本模块的某个函数中导入外部模块变量
只在该函数中访问, 在本模块、本模块其他函数中都无法访问外部模块变量
4 import 导入模块,多次执行, 实际只执行第一次
"""
import test_module

b = 8

def f1():
test_module.a = 5

def f2():
def f22():
print test_module.a
f22()

def f3():
print b # 第一次使用 b 是 读取,是全局变量

def f4():
b = 9 # 第一次使用 b 是 赋值,是函数局部变量

def f5():
global b # 强制全局变量
b = 9

print test_module.a
f1()
print test_module.a
f2()
print test_module.a

import test_module # 再次执行导入模块,不会再执行了
print test_module.a

print '-------1'
f3()
print b
f4()
print b
f5()
print b
f3()

"""
Out:
3
5
5
5
5
-------1
8
8
8
9
9

"""

 

test_module.py:

# -*- coding: utf-8 -*-
a = 3

猜你喜欢

转载自www.cnblogs.com/sunzebo/p/9572196.html