python override __new__无法向__init__发送参数

问题描述 投票:2回答:1

我有一个非常简单的程序,它有一个单例实现为基类,它只是定义了一个用于实现“单一”的新东西。但是我不能再向init方法发送参数 - 当我这样做时,我从单例新的超级调用中得到一个“TypeError:object()不参数”:

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
python singleton new-operator
1个回答
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 来创建对象:

In [64]: OneOfAKind() == OneOfAKind()
--> OneOfAKind __init__
Out[64]: True

In [65]: OneOfAKind() == OneOfAKind()
Out[65]: True

In [66]: OneOfAKind() == OneOfAKind2('foo')
Out[66]: False

然后:

qazxswpoi
© www.soinside.com 2019 - 2024. All rights reserved.