2012-09-28 53 views
1

編輯:正如我剛發現的,「Singleton」在python中沒有用處。 python改爲使用「Borg」。 http://wiki.python.de/Das%20Borg%20Pattern博格我能讀&寫入全局變量,從喜歡不同類別:讀寫全局變量和列表

b1 = Borg() 
b1.colour = "red" 
b2 = Borg() 
b2.colour 
>>> 'red' 

但我能夠創建/讀取列表博格這樣的:

b1 = Borg() 
b1.colours = ["red", "green", "blue"] 
b2 = Borg() 
b2.colours[0] 

這是Borg不支持的東西?如果是:我如何創建全局列表,我可以從不同的類中讀取&?


原題:

我想讀&寫從不同類別的全局變量。僞代碼:

class myvariables(): 
    x = 1 
    y = 2 

class class1(): 
    # receive x and y from class myvariables 
    x = x*100 
    y = y*10 
    # write x and y to class myvariables 

class class2(): 
    # is called *after* class1 
    # receive x and y from class myvariables 
    print x 
    print y 

printresult應該是「100」和「20」。 我聽說「Singleton」可以做到這一點...但我沒有找到任何關於「Singleton」的好解釋。我怎樣才能使這個簡單的代碼工作?

回答

2

Borg模式類attrs不會在新的實例調用上重置,但實例attrs會。如果要保留以前設置的值,請​​確保您使用的是類attrs而不是實例attrs。下面的代碼將做你想要的。

class glx(object): 
    '''Borg pattern singleton, used to pass around refs to objs. Class 
    attrs will NOT be reset on new instance calls (instance attrs will). 
    ''' 
    x = '' 
    __sharedState = {} 
    def __init__(self): 
     self.__dict__ = self.__sharedState 
     #will be reset on new instance 
     self.y = '' 


if __name__ == '__main__': 
    gl = glx() 
    gl.x = ['red', 'green', 'blue'] 
    gl2 = glx() 
    print gl2.x[0] 

爲了證明這一點,請使用實例attr y再次嘗試。你會得到一個不愉快的結果。

祝你好運, Mike