[Tutor] static method

Christian Tismer tismer@appliedbiometrics.com
Tue, 14 Dec 1999 15:30:22 +0100


"Yanko, Curtis (GSP)" wrote:
> 
> How can we use this to implement a Singleton Pattern?

Well, you can do it. I just looked singletons up at
http://www.cs.monash.edu.au/~damian/CSC2050/Topics/09.18.OODesign4/html/text.html#the_singleton_pattern

but if you just want a singleton, it really doesn't matter whether
this is a class or an instance, so this thingie does it:

>>> class Singleton:
... 	def __init__(self):
... 		global Singleton
... 		Singleton = self
... 	def __call__(self):
... 		return self
... 
>>> 
>>> y=Singleton()
>>> x=Singleton()
>>> x is y
1

Yes it is a cricular reference. Yes it is dynamic rewrite of
a class. Yes it behaves right.

>>> x.func = lambda x:x+1
>>> y.func(3)
4
>>> 

Why? Well, in this case I've put the idea upside down.
Assigning a function to an instance does *not* try to
bind it, and we are there :-)

This all makes not much of sense if you need access to 'self',
so put your real methods into the class before overwriting.

ciao - chris

-- 
Christian Tismer             :^)   <mailto:tismer@appliedbiometrics.com>
Applied Biometrics GmbH      :     Have a break! Take a ride on Python's
Kaiserin-Augusta-Allee 101   :    *Starship* http://starship.python.net
10553 Berlin                 :     PGP key -> http://wwwkeys.pgp.net
PGP Fingerprint       E182 71C7 1A9D 66E9 9D15  D3CC D4D7 93E2 1FAE F6DF
     we're tired of banana software - shipped green, ripens at home