R
Rajarshi Guha
Hi, I'm having a little problem with understanding the working of a
singleton and borg class. Basically I nedd an class whose state will be
shared across several modules. I found the stuff on the ASPN cookbook but
it does'nt seem to be working for me. I've included some code:
Borg.py:
--------
class Borg:
__shared_state = {}
def __init__(self):
self.__dict__ = self.__shared_state
self.val = {}
class Singleton(object):
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
class Tester(Singleton):
def __init__(self):
self.val = {}
t.py:
-----
import Borg,v
x = Borg.Tester()
x.val['a'] = 1
print x.val
v.func()
print x.val
v.py:
-----
import Borg
def func():
y = Borg.Tester()
print y.val, '...from t.py'
y.val['a'] = 2
return
I had expected to see:
{'a':1}
{'a':1} ...from t.py
{'a':2}
However I get
{'a':1}
{} ...from t.py
{'a':2}
Should'nt the instantiation of val in v.func() just use the val that was
already created when it was instatntiated in t.py?
I just cant seem to wrap my head around this oen, so any suggestions
would be appreciated.
Thanks
singleton and borg class. Basically I nedd an class whose state will be
shared across several modules. I found the stuff on the ASPN cookbook but
it does'nt seem to be working for me. I've included some code:
Borg.py:
--------
class Borg:
__shared_state = {}
def __init__(self):
self.__dict__ = self.__shared_state
self.val = {}
class Singleton(object):
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
class Tester(Singleton):
def __init__(self):
self.val = {}
t.py:
-----
import Borg,v
x = Borg.Tester()
x.val['a'] = 1
print x.val
v.func()
print x.val
v.py:
-----
import Borg
def func():
y = Borg.Tester()
print y.val, '...from t.py'
y.val['a'] = 2
return
I had expected to see:
{'a':1}
{'a':1} ...from t.py
{'a':2}
However I get
{'a':1}
{} ...from t.py
{'a':2}
Should'nt the instantiation of val in v.func() just use the val that was
already created when it was instatntiated in t.py?
I just cant seem to wrap my head around this oen, so any suggestions
would be appreciated.
Thanks