issue with singleton python call two times __init__

前端 未结 4 391
感情败类
感情败类 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条回答
  •  萌比男神i
    2020-12-10 07:45

    PEP 318 has an example of a singleton decorator for classes:

    def singleton(cls):
        instances = {}
        def getinstance():
            if cls not in instances:
                instances[cls] = cls()
            return instances[cls]
        return getinstance
    
    @singleton
    class MyClass:
        ...
    

    (though I haven't used it myself.)

    Btw, about...

    I made a singleton like this

    Also, you should mention that you copied it directly from ActiveState.

提交回复
热议问题