implementing a constant singleton

Duncan Booth duncan at NOSPAMrcp.co.uk
Tue Mar 26 07:56:58 EST 2002


"robin and jim" <robinjim at earthlink.net> wrote in 
news:p4_n8.1650$Ya2.72647 at newsread1.prod.itd.earthlink.net:

> Is this the way to implement a constant singleton class using Python 2.2
> "new-style" classes?
If you really feel a need for singletons, then I suppose this is a way to 
do them. Personally, I prefer to avoid singletons if possible.
 
> class Message(str):
> 
>    def __new__(this_class, specification):
>       print 'Message.__new__ applied by %s' % str(this_class)
        self = str.__new__(this_class, specification)
>       self.subject = specification[0]
>       self.body = specification[1:]
Running __new__ and __init__ together gets round your issue with __init__ 
being called every time.

> class Constant_Singleton_Message(Message):
> 
>    def __new__(this_class):
>       it = this_class.__dict__.get('__it__')
Don't use __it__ as it is reserved for Python.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?



More information about the Python-list mailing list