gpt4 book ai didi

python - 模块范围内的全局关键字

转载 作者:太空宇宙 更新时间:2023-11-03 18:04:56 24 4
gpt4 key购买 nike

我有一个包含以下几行的 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

同时

>>> 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

关于python - 模块范围内的全局关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27066509/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com