python override __new__无法向__init__发送参数
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python override __new__无法向__init__发送参数相关的知识,希望对你有一定的参考价值。
我有一个非常简单的程序,它有一个单例实现为基类,它只是定义了一个用于实现“单一”的新东西。但是我不能再向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
是的,因为你继承自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
以上是关于python override __new__无法向__init__发送参数的主要内容,如果未能解决你的问题,请参考以下文章
Python(和 Python C API):__new__ 与 __init__
详解Python中的__new__、__init__、__call__三个特殊方法