编辑:正如我刚刚发现的,"Singleton“在python中并不那么有用。python使用"Borg“代替。使用Borg I的http://wiki.python.de/Das%20Borg%20Pattern能够从不同的类读取和写入全局变量,如:
b1 = Borg()
b1.colour = "red"
b2 = Borg()
b2.colour
>>> 'red'但我是,不能用borg创建/读取列表,如下所示:
b1 = Borg()
b1.colours = ["red", "green", "blue"]
b2 = Borg()
b2.colours[0]这是博格不支持的吗?如果是:我如何创建全局列表,我可以从不同的类读和写?
原题:
我想读和写来自不同类的全局变量。伪码:
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”。我听说“辛格尔顿”能做到这一点。但我没有找到任何关于“辛格尔顿”的好解释。我如何使这个简单的代码工作?
发布于 2012-09-29 02:35:08
在新的实例调用时,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]为了证明这一点,再试一次,你会得到一个不愉快的结果。
祝你好运迈克
https://stackoverflow.com/questions/12639205
复制相似问题