On Jul 3, 6:58 pm, Urizev <[EMAIL PROTECTED]> wrote: > Hi everyone > > I have developed the singleton implementation. However I have found a > strange behaviour when using from different files. The code is > attached. > > Executing main > new MySet object > No singleton instance > New singleton: > <__main__.Singleton instance at 0x2b98be474a70> > new MySet object > There is a singlenton instance > new Member > new MySet object > No singleton instance > New singleton: > <myset.Singleton instance at 0x2b98be474d88> > new Member > new MySet object > There is a singlenton instance > new Member > new MySet object > There is a singlenton instance > > I do not know why, but it creates two instances of the singleton. Does > anybody know why?
Because __init__() is called to initialize the state of an object *after* it has already been created. You should create a "new-style" class and define __new__() instead. Here's a working version: class Singleton(object): # new-style class def __new__(cls, *args, **kwds): # return the singleton (if already created) try: return cls.__dict__['__singleton'] except KeyError: # raised only the first time for a given class # create the singleton and store it to the class namespace singleton = object.__new__(cls, *args, **kwds) setattr(cls, '__singleton', singleton) return singleton class X(Singleton): def __init__(self, a): self.a = a assert X(1) is X(2) Note however that the classic Singleton pattern is usually frowned upon in Python; the preferred approach is to use (module level) globals. Also search for the "Borg pattern". George -- http://mail.python.org/mailman/listinfo/python-list