2016-12-04 10 views
0

當使用內置函數globals()時,它似乎是這樣做的:當我嘗試訪問一個全局值時, (不是類全球,因爲它會被每個初始化覆蓋全球的我做了應該保存及使用不管類的許多初始化怎麼有當在一個類中使用全局變量時,它不會返回模塊級全局變量,而只會發生錯誤

像一些示例代碼:。

somevalue = False 

class SomeClass(object): 
    """ 
    ... 
    """ 
    def __init__(self): 
     self.change_global_value() 

    def change_global_value(self): 
     """ 
     Changes global module values that this class is in. 
     """ 
     globals().somevalue = True # Error. (line 14) 
     self.__module__.globals().somevalue = True # Error. (line 14, after some changes) 
     somevalue = True # Error as well. (line 14, after some more changes) 

發生的回溯:

Traceback (most recent call last): 
    File "<stdin>", line 14, in <module> 
    globals().somevalue = True # Error. 
AttributeError: 'dict' object has no attribute 'somevalue' 

Traceback (most recent call last): 
    File "<stdin>", line 14, in <module> 
    self.__module__.globals().somevalue = True # Error. 
AttributeError: 'str' object has no attribute 'globals' 

Traceback (most recent call last): 
    File "<stdin>", line 14, in change_global_value 
    somevalue = True # Error as well. 
UnboundLocalError: local variable 'somevalue' referenced before assignment 
+1

請注意,由於您有一個類,更好的方法是使用類級變量。 –

回答

2

globals()返回dict這樣你就可以使用globals()['somevalue'] = 'newvalue'賦新值:

somevalue = False 

class SomeClass(object): 
    """ 
    ... 
    """ 
    def __init__(self): 
     self.change_global_value() 

    def change_global_value(self): 
     """ 
     Changes global module values that this class is in. 
     """ 
     globals()['somevalue'] = True 

的首選形式僅僅是定義一個變量作爲全球:

somevalue = False 

class SomeClass(object): 
    """ 
    ... 
    """ 
    def __init__(self): 
     self.change_global_value() 

    def change_global_value(self): 
     """ 
     Changes global module values that this class is in. 
     """ 
     global somevalue 
     somevalue = True 

注意這通常是一個壞在一般情況下,特別是在課堂上練習。