python 覆盖 __new__ 无法将参数发送到 __init__

标签 python singleton new-operator

我有一个非常简单的程序,它有一个作为基类实现的单例,它简单地定义了一个用于实现“单一性”的 new。但是,我无法再向 init 方法发送参数 - 当我这样做时,我从单例 new super 调用中收到“TypeError: object() takes no parameters”:

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

最佳答案

是的,因为 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

关于python 覆盖 __new__ 无法将参数发送到 __init__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48039587/

相关文章:

python动态类名

java - 是否同步 PoolingClientConnectionManager

java - CDI 1.1 使用后立即处置注入(inject)的资源

c++ - 为什么我们能够访问类中未分配的内存?

c++ - 在派生类中重写运算符 new/delete

C++ 内存管理

python - 为什么在 Scheme 和 Python 中实现的递归方程的返回值不同?

javascript - Flask/jinja 发送数组到 javascript

python - Matplotlib 使用 for 循环显示多个图像

c# - 在自定义成员资格提供程序类中使用单例模式