Assigning to self
top
alexandre.tp at gmail.com
Sat Feb 12 17:59:01 EST 2005
Jeff Shannon wrote:
> class __Foo:
> "I am a singleton!"
> pass
>
> def Foo(foo_obj = __Foo()):
> assert isinstance(foo_obj, __Foo
> return foo_obj
this is a bit simpler, I think, and takes advantage from Python's free
name-rebinding.
class Singleton(object):
def __call__(self):
return self
Singleton = Singleton()
And, now, every time you say obj = Singleton(), you're getting the same
instance. Of course, this corrupt the __call__ method of the class, and
isn't inheritance-safe at all, but if you want only one or two classes
like this, it isn't very much work to implement it. Also, it's free of
weird metaclasses, __new__s, or __dict__ hacks, I think.
Just putting my two-cents into this,
--
- Alexandre
More information about the Python-list
mailing list