我假设我是* args和** kwargs的乞be。我正在尝试制作一些模拟代码,以模仿在此论坛和网络上其他地方所看到的内容。但是,当我尝试执行与所见内容相似的操作时,收到了意外错误。这是示例:
enter code here class A():
defined = []
def __new__(cls, *args, **kwargs):
new = kwargs['new']
if not new and len(A.defined)>0:
x = A.defined[0]
else:
# x = super().__new__(cls, *args, **kwargs)
# if I use this, it raises error:
# "TypeError: object.__new__() takes exactly one argument (the type to instantiate)"
x = super().__new__(cls)
# this works
return x
def __init__(self, value, *args, **kwargs):
self.value = value
A.defined.append(self)
a = A("a", new = True)
为什么会出现此错误?
谢谢。
当使用super().__new__
时,它是__new__
类的object
方法,它仅接受一个参数(cls
)。由于您还向其转发了*args, **kwargs
参数,因此基本上是将(cls, new=True)
发送到只需要(cls)
希望的