单例python调用问题两次__init__

Ste*_*gán 4 python singleton init

我有一个像这样的单身人士

class Singleton:

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

    __instance = None

    def __init__(self):
        # Check whether we already have an instance
        if Singleton.__instance is None:
            Singleton.__instance = Singleton.__impl()

        # Store instance reference as the only member in the handle
        self.__dict__['_Singleton__instance'] = Singleton.__instance

    def __getattr__(self, attr):
        """ Delegate access to implementation """
        return getattr(self.__instance, attr)

    def __setattr__(self, attr, value):
        """ Delegate access to implementation """
        return setattr(self.__instance, attr, value)
Run Code Online (Sandbox Code Playgroud)

当我做了几个Singleton的实例时,我得到了两个init的调用,我的意思是"INIT"被打印了两次,我觉得它不应该发生

有人知道这有什么问题或有更好的方法来实现这个?

mgi*_*son 9

这是编写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)
Run Code Online (Sandbox Code Playgroud)

虽然可能有更好的方法.我不得不承认我从未喜欢过单身人士.我更喜欢工厂类型的方法:

class Foo(object):
    pass

def foo_singleton_factory(_singlton = Foo()):
    return _singleton

a = foo_singleton_factory()
b = foo_singleton_factory()
print (a is b)
Run Code Online (Sandbox Code Playgroud)

这样做的好处是,如果你需要,你可以继续获得相同的Foo实例,但如果你决定在10年后不想要一个真正的单身人士,那么你不仅限于一个实例.

  • 不,默认参数只被评估一次 - 创建函数时.他们没有为后续的电话重新评估.这是python中各种混乱的根源:-).有关获取人员的另一个案例,请参见http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument. (2认同)

ane*_*oid 7

PEP 318有一个类的单例装饰器的例子:

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

@singleton
class MyClass:
    ...
Run Code Online (Sandbox Code Playgroud)

(虽然我自己没有用过它.)

顺便说一句,关于......

我做了一个像这样的单身人士

另外,您应该提到您直接从ActiveState复制它.