2012-09-28 58 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