模块范围内的全局关键字

2024-04-21

我有一个 Python 文件,其中包含以下几行:

import sys

global AdminConfig
global AdminApp

该脚本在 Jython 上运行。我理解在函数内部使用 global 关键字,但是在模块级别使用“global”关键字意味着什么?


global x更改范围规则x 在当前范围内到模块级别,所以当x已经在模块级别了,它没有任何作用。

澄清:

>>> def f(): # uses global xyz
...  global xyz
...  xyz = 23
... 
>>> 'xyz' in globals()
False
>>> f()
>>> 'xyz' in globals()
True

while

>>> def f2():
...  baz = 1337 # not global
... 
>>> 'baz' in globals()
False
>>> f2() # baz will still be not in globals()
>>> 'baz' in globals()
False

but

>>> 'foobar' in globals()
False
>>> foobar = 42 # no need for global keyword here, we're on module level
>>> 'foobar' in globals()
True

and

>>> 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

模块范围内的全局关键字 的相关文章

随机推荐