zoukankan      html  css  js  c++  java
  • [b0020] 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
  • 相关阅读:
    20131001国庆作业例2-10,2-11
    20131001国庆作业例2-7,2-8,2-9
    20131001国庆作业例2-4,2-5,2-6
    20131001国庆作业第二章例2-1,2-2,2-3
    20131001国庆作业第一章例1-1
    20130930C语言作业基础练习
    编程心得4
    编程心得3
    编程心得1
    714
  • 原文地址:https://www.cnblogs.com/sunzebo/p/9572196.html
Copyright © 2011-2022 走看看