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

test_module2.py:

 

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

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

reload(test_module) # reload 重新真正运行模块
print test_module.a

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

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

"""

test_module.py:

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

 

转载于:https://www.cnblogs.com/sunzebo/p/9572196.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值