2014-11-21 116 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