Le Saturday 28 June 2008 03:47:43 Casey McGinty, vous avez écrit :
Well, it works !
__state = {}
def __init__(self):
self.__dict__ = self.__state
.....:
.....:
...[161]: 5
but the __dict__ attribute is the container of attributes of an instance,
which are not used in the underlying implementation of dictinnaries.
Yes it is, but it's rather unneeded in Python, we prefer simply create a
module level dictionnary, these tricks are used in language like C++ or Java.
In python :
mymodule.py :
ModuleOptions = {}
othermodule.py :
import mymodule
mymodule.Module Options['Verbose'] = True
or if you think encapsulation is important :
mymodule.py :
_ModuleOptions = {}
def get_option(opt) :
return _ModuleOptions[opt]
....
And you're done.
--
_____________
Maric Michaud
On Fri, Jun 27, 2008 at 3:21 PM, Casey McGinty <casey.mcginty@ gmail.com>
>
wrote:
>
>
wrote:
Hi,
I'm trying to implement a simple Borg or Singleton pattern for a class
that inherits from 'dict'. Can someone point out why this code does not
work?
class MyDict( dict ):
__state = {}
def __init__(self):
self.__dict__ = self.__state
a = MyDict()
a['one'] = 1
a['two'] = 2
print a
print MyDict()
I'm trying to implement a simple Borg or Singleton pattern for a class
that inherits from 'dict'. Can someone point out why this code does not
work?
class MyDict( dict ):
__state = {}
def __init__(self):
self.__dict__ = self.__state
a = MyDict()
a['one'] = 1
a['two'] = 2
print a
print MyDict()
>>>[156]: class MyDict( dict ):
def __init__(self):
self.__dict__ = self.__state
.....:
.....:
>>>[160]: MyDict().toto = 5
>>>[161]: MyDict().toto
but the __dict__ attribute is the container of attributes of an instance,
which are not used in the underlying implementation of dictinnaries.
This looks like a good solution:
>
class MyDict( dict ):
def __new__(cls,*p, **k):
if not '_instance' in cls.__dict__:
cls._instance = dict.__new__(cl s)
return cls._instance
>
class MyDict( dict ):
def __new__(cls,*p, **k):
if not '_instance' in cls.__dict__:
cls._instance = dict.__new__(cl s)
return cls._instance
module level dictionnary, these tricks are used in language like C++ or Java.
In python :
mymodule.py :
ModuleOptions = {}
othermodule.py :
import mymodule
mymodule.Module Options['Verbose'] = True
or if you think encapsulation is important :
mymodule.py :
_ModuleOptions = {}
def get_option(opt) :
return _ModuleOptions[opt]
....
And you're done.
--
_____________
Maric Michaud