代码之家  ›  专栏  ›  技术社区  ›  jcomeau_ictx

如何为导入的全局变量赋值?

  •  1
  • jcomeau_ictx  · 技术社区  · 5 年前

    这么多年了,我还是不喜欢用Python来搜索globals。我的问题出现在一个uWSGI应用程序中,在哪里 init() BROWSER = webdriver.Firefox() 申报后 global BROWSER

    globaltest.py :

    #!/usr/bin/python3
    '''
    Test of keyword `global`
    '''
    GLOBALTEST = None
    
    def init():
        global GLOBALTEST
        GLOBALTEST = 'Something'
    
    if __name__ == '__main__':
        print('before init: GLOBALTEST', GLOBALTEST)
        init()
        print(' after init: GLOBALTEST', GLOBALTEST)
    

    执行:

    jcomeau@bendergift:/tmp$ ./globaltest.py 
    before init: GLOBALTEST None
     after init: GLOBALTEST Something
    jcomeau@bendergift:/tmp$ python3
    Python 3.7.3 (default, Apr  3 2019, 05:39:12) 
    [GCC 8.3.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> from globaltest import *
    >>> GLOBALTEST
    >>> init()
    >>> GLOBALTEST
    >>> 
    
    1 回复  |  直到 5 年前
        1
  •  2
  •   chepner    5 年前

    真正地 全局:内置范围。“全球”范围实际上是一个 模块 全局范围,程序中的每个模块都有一个。

    名为的全局变量 GLOBALTEST 在互动会话中。一个是模块的全局范围的一部分 globaltest ; 另一个是交互式会话的全局范围的一部分,模块 __main__ .

    init 设置的值 globaltest.GLOBALTEST ,因为Python使用词法范围。您正在检查 __main__.GLOBALTEST 初始化

    如果你检查 全球测试 ,你会看到的 它的 价值变化:

    >>> import globaltest
    >>> globaltest.GLOBALTEST
    >>> init()
    >>> globaltest.GLOBALTEST
    'Something'
    >>> GLOBALTEST
    >>>