singleton decorator
Wildemar Wildenburger
wildemar at freakmail.de
Tue Aug 8 08:50:39 EDT 2006
Pedro Werneck wrote:
>>>> class Singleton(object):
> ... def __new__(cls, *args, **kwds):
> ... try:
> ... return cls._it
> ... except AttributeError:
> ... cls._it = object.__new__(cls, *args, **kwds)
> ... return cls._it
>
> But __init__ will be called once for each time you call A, even if it's
> always the same instance returned. If this is a problem, you'll need
> another method to use for initialization and call it only once.
>
Or you could always just use the __new__() method instead of __init__(),
putting all your initialization into the above except-block. If you
replace 'cls._it = ...' with 'self = cls_it = ...' you'll feel right at
home too :).
Anything 'unpythonic' (gosh how I hate that word ;)) about that, BTW?
c.u.
wildemar
More information about the Python-list
mailing list