gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 17:47:00 27 4
gpt4 key购买 nike

我有一个非常简单的程序,它有一个作为基类实现的单例,它简单地定义了一个用于实现“单一性”的 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com