我有一个非常简单的程序,它有一个单例实现为基类,只是定义了一个 new ,用于实现“单一”。但是我不能再向 init 方法发送参数 - 当我这样做时,我会从单例新超级调用中获得“TypeError:object()不参数”:< / p>
class Singleton(object):
_instances = {}
def __new__(cls, *args, **kwargs):
print(args, kwargs)
if cls._instances.get(cls, None) is None:
cls._instances[cls] = super(Singleton, cls).__new__(cls, *args, **kwargs)
return Singleton._instances[cls]
class OneOfAKind(Singleton):
def __init__(self):
print('--> OneOfAKind __init__')
Singleton.__init__(self)
class OneOfAKind2(Singleton):
def __init__(self, onearg):
print('--> OneOfAKind2 __init__')
Singleton.__init__(self)
self._onearg = onearg
x = OneOfAKind()
y = OneOfAKind()
print(x == y)
X = OneOfAKind2('testing')
输出结果为:
() {}
Traceback (most recent call last):
File "./mytest.py", line 29, in <module>
x = OneOfAKind()
File "./mytest.py", line 10, in __new__
cls._instances[cls] = super(Singleton, cls).__new__(cls, (), {})
TypeError: object() takes no parameters
答案 0 :(得分:0)
是的,因为object
是你从super
继承并从In [54]: object('foo', 'bar')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-54-f03d0963548d> in <module>()
----> 1 object('foo', 'bar')
TypeError: object() takes no parameters
调用的,所以不会采取任何参数:
metaclass
如果您想要执行此类操作,我建议使用__new__
而不是子类,而不是覆盖metaclass
__call__
覆盖import six ## used for compatibility between py2 and py3
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if Singleton._instances.get(cls, None) is None:
Singleton._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return Singleton._instances[cls]
@six.add_metaclass(Singleton)
class OneOfAKind(object):
def __init__(self):
print('--> OneOfAKind __init__')
@six.add_metaclass(Singleton)
class OneOfAKind2(object):
def __init__(self, onearg):
print('--> OneOfAKind2 __init__')
self._onearg = onearg
来创建对象:< / p>
In [64]: OneOfAKind() == OneOfAKind()
--> OneOfAKind __init__
Out[64]: True
In [65]: OneOfAKind() == OneOfAKind()
Out[65]: True
In [66]: OneOfAKind() == OneOfAKind2('foo')
Out[66]: False
然后:
|TInterface\ICONS\inv_offhand_1h_ulduarraid_d_01:24:24:1.75:1.75|t Rest of description