issue with singleton python call two times __init__

前端 未结 4 385
感情败类
感情败类 2020-12-10 07:30

I have a singleton like this

class Singleton:

    class __impl:
        def __init__(self):
            print \"INIT\"

    __instance = None

    def __ini         


        
4条回答
  •  情歌与酒
    2020-12-10 07:44

    Here's a slightly simpler way to write a Singleton:

    class Singleton(object):
        __instance = None
        def __new__(cls):
            if cls.__instance is None:
                cls.__instance = super(Singleton,cls).__new__(cls)
                cls.__instance.__initialized = False
            return cls.__instance
    
        def __init__(self):      
            if(self.__initialized): return
            self.__initialized = True
            print ("INIT")
    
    a = Singleton()
    b = Singleton()
    print (a is b)
    

    although there may be better ways. I have to admit that I've never been fond of singletons. I much prefer a factory type approach:

    class Foo(object):
        pass
    
    def foo_singleton_factory(_singlton = Foo()):
        return _singleton
    
    a = foo_singleton_factory()
    b = foo_singleton_factory()
    print (a is b)
    

    This has the advantage that you can keep getting the same instance of Foo if you want it, but you're not limited to a single instance if you decide 10 years down the road that you don't want a true singleton.

提交回复
热议问题