我预感到我是个讨饭的人。我试图制作一些模拟代码,模仿我在这个论坛和网上其他地方看到的做法。然而,当我尝试做一些类似于我所看到的事情时,我收到了一个意外的错误。例如:
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__
时,它是object
类的__new__
方法,它只接受一个参数(cls
)。由于您还将*args, **kwargs
参数转发给它,因此基本上是将(cls, new=True)
发送给只需要(cls)
的方法希望这是有道理的
相关问题 更多 >
编程相关推荐