2014-11-21 82 views
1

Global关键字我有以下行Python文件:在模块范围

import sys 

global AdminConfig 
global AdminApp 

这个脚本在运行的Jython。我理解在函数内部使用全局关键字,但在模块级别使用“全局”关键字意味着什么?

+0

此信息可能是对你有用http://stackoverflow.com/questions/4693120/use-of-global-keyword-in-python – AtAFork 2014-11-21 17:02:01

+0

这是什么意思?一点都没有。编写此代码的人对关键字的作用无知或错误。 – 2014-11-21 17:04:56

+0

这些对象“AdminConfig”和“AdminApp”由Webpshere Application Server实现,此文件使用它们,另一个问题是它们是如何填满的?唯一的输入是sys模块 – tt0686 2014-11-21 17:08:29

回答

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