【问题标题】:Global keyword on module scope模块范围的全局关键字
【发布时间】:2014-11-21 16:59:49
【问题描述】:

我有一个包含以下几行的 Python 文件:

import sys

global AdminConfig
global AdminApp

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

【问题讨论】:

  • 这篇文章可能对你有用stackoverflow.com/questions/4693120/…
  • 什么意思?什么都没有。编写此代码的人对关键字的作用一无所知或错误。
  • 那些对象“AdminConfig”和“AdminApp”由Webpshere应用服务器实现,这个文件使用它们,我的另一个问题是它们是如何被填充的?唯一的导入是 sys 模块

标签: python websphere jython wsadmin


【解决方案1】:

global xx 在当前范围内 的范围规则更改为模块级别,因此当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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 2016-06-06
    • 1970-01-01
    • 1970-01-01
    • 2013-11-28
    • 2019-01-02
    • 2015-12-02
    相关资源
    最近更新 更多