读写全局变量和列表

2024-04-27 09:20:10 发布

您现在位置:Python中文网/ 问答频道 /正文

编辑:正如我刚刚发现的,“Singleton”在python中没有那么有用。python使用“Borg”代替。http://wiki.python.de/Das%20Borg%20Pattern使用Borg,我能够读写来自不同类的全局变量,例如:

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

但我没有能够创建/阅读一个与博格人类似的列表:

^{pr2}$

这是博格不支持的吗?如果是:如何创建可以从不同类读写的全局列表?在


原题:

我想读写来自不同类的全局变量。伪代码:

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

打印结果应为“100”和“20”。 我听说“单身汉”可以做到。。。辛格尔顿没有找到任何好的解释。如何使这个简单的代码工作?在


Tags: and代码from列表redb2borgclass
1条回答
网友
1楼 · 发布于 2024-04-27 09:20:10

新的实例调用不会重置Borg模式类属性,但会重置实例属性。如果要保留先前设置的值,请确保使用的是类属性而不是实例属性。下面的代码可以满足您的需要。在

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]

为了证明这一点,请用实例属性再试一次。你会得到不满意的结果。在

祝你好运, 迈克

相关问题 更多 >