我有一个Python文件,其中包含以下行:
import sys
global AdminConfig
global AdminApp
此脚本在Jython上运行。我理解在函数内部使用全局关键字,但在模块级别使用“global”关键字意味着什么呢?
答案 0 :(得分:1)
global x
将当前范围中x
的范围规则更改为模块级别,因此当x
已经处于模块级别时,它没有用处
澄清:
>>> def f(): # uses global xyz
... global xyz
... xyz = 23
...
>>> 'xyz' in globals()
False
>>> f()
>>> 'xyz' in globals()
True
,而
>>> def f2():
... baz = 1337 # not global
...
>>> 'baz' in globals()
False
>>> f2() # baz will still be not in globals()
>>> 'baz' in globals()
False
但是
>>> 'foobar' in globals()
False
>>> foobar = 42 # no need for global keyword here, we're on module level
>>> 'foobar' in globals()
True
和
>>> global x # makes no sense, because x is already global IN CURRENT SCOPE
>>> x=1
>>> def f3():
... x = 5 # this is local x, global property is not inherited or something
...
>>> f3() # won't change global x
>>> x # this is global x again
1