5

我正在使用以下代码在 python 中实例化一个单例:

class Singleton(type):
    def __init__(cls, name, bases, dic):
        super(Singleton, cls).__init__(name, bases, dic)
        cls.instance = None

    def __call__(cls, *args, **kwargs):
        if cls.instance is None:
            if DEBUG:
                print("Creating NEW Orchestrator instance")
        else:
            if DEBUG:
                print("Using EXISTING Orchestrator instance")

            cls.instance = super(Singleton, cls).__call__(*args, **kwargs)

        return cls.instance

初始化看起来像这样:

def __init__(self, arg=None):
    ...

当我实例化对象时,它似乎不接受这个论点:

Obj = Object("parameter")

arg 不等于"parameter"。它是无。

我认为这是将 *args 传递给call的目的。第一次实例化单例时如何传递参数?

4

2 回答 2

3

对于您当前Singleton的课程,以下内容似乎在 Python 3.x 上运行良好(我假设您正在使用基于该函数的print函数。

class Object(metaclass=Singleton):
    def __init__(self, arg=None):
        print("creating instance with arg:", arg)

例如:

>>> Object("parameter")
creating NEW Orchestrator instance
creating instance with arg: parameter
<__main__.Object object at 0x7f45f9ce8910>
>>> Object("foobar")   # returns the same instance as the above call
<__main__.Object object at 0x7f45f9ce8910>

编辑:你可以在 Python 2.x 上做同样的事情,指定元类的语法有点不同:

class Object(object):
    __metaclass__ = Singleton
    def __init__(self, arg=None):
        print("creating instance with arg:", arg)
于 2013-06-19T23:13:39.227 回答
2

最好像这样使用它:

class Singleton(type):
    def __init__(cls,name,bases,dic):
        super(Singleton,cls).__init__(name,bases,dic)
        cls.instance=None
    def __call__(cls,*args,**kw):
        if cls.instance is None:
            cls.instance=super(Singleton,cls).__call__(*args,**kw)
        return cls.instance

class Object(object):
    __metaclass__ = Singleton
    def __init__(self, a=None):
        print a 

c = Object("parameter")

我想...

注意:这适用于 Python 2.7.4

于 2013-06-19T23:10:26.157 回答