implementing a constant singleton
robin and jim
robinjim at earthlink.net
Tue Mar 26 07:46:13 EST 2002
Is this the way to implement a constant singleton class using Python 2.2
"new-style" classes?
class Message(str):
def __new__(this_class, specification):
print 'Message.__new__ applied by %s' % str(this_class)
return str.__new__(this_class, specification)
def __init__(self, specification):
print 'Message.__init__ applied by %s' % str(self)
self.subject = specification[0]
self.body = specification[1:]
# additional Message class methods go here
class Constant_Singleton_Message(Message):
def __new__(this_class):
it = this_class.__dict__.get('__it__')
if it is not None:
return it
this_class.__it__ = it = Message.__new__(this_class,
this_class.set_string())
return it
## def init(self):
## Message.__init__(self, self.set_string())
def __init__(self):
Message.__init__(self, self.set_string())
def set_string():
return "I'm a constant singleton"
set_string = staticmethod(set_string)
## end implementation--------------------------
I'm troubled by the fact that Message.__init__ is applied each time
Constant_Singleton_Message is "created", but I see no way to avoid it.
Thanks in advance for your feedback.
More information about the Python-list
mailing list