zoukankan      html  css  js  c++  java
  • Python之全局变量篇

    python里面全局变量有两种灵活的用法:

    1 声明法

    在文件开头声明全局变量

    在具体函数中使用该变量时,需要事先声明 global variable,否则系统将该变量视为局部变量。

    CONSTANT = 0                                  #定义了一个全局变量,最好将全局变量大写


    def modifyConstant() :
            global CONSTANT                     #在方法体中要使用全局变量,要先进行声明
            print ‘CONSTANT_1=%d’  %CONSTANT
            CONSTANT += 1
            return

    if __name__ == '__main__' :
            modifyConstant()
           print ‘CONSTANT_2=%d’  %CONSTANT

    输出结果:

    CONSTANT_1=0

    CONSTANT_2=1

    2模块法(推荐)

    把全局变量定义在一个单独的模块中:
    #gl.py
    gl_1 = 'hello'
    gl_2 = 'world'

    在其它模块中使用
    #a.py
    import gl

    def hello_world()
        print gl.gl_1, gl.gl_2

    #b.py
    import gl

    def fun1()
        gl.gl_1 = 'Hello'
        gl.gl_2 = 'World'

    第二种方法,适用于不同文件之间的变量共享,而且一定程度上避免了开头所说的全局变量的弊端,推荐!

  • 相关阅读:
    jq insertBefore 的返回值
    微信公众号-定位之地址逆解析&导航
    微信JS-SDK
    Vue
    ES6-函数的扩展
    ES6-数组的扩展
    JSP
    JS
    HTML+CSS
    jdbc操作数据库
  • 原文地址:https://www.cnblogs.com/sallybin/p/3061021.html
Copyright © 2011-2022 走看看