为什么以下代码出错?
class Foo:
def __new__(cls, *args, **kwargs):
print("Creating Instance")
instance = super(Foo, cls).__new__(cls,*args, **kwargs)
return instance
def __init__(self, a, b):
self.a = a
self.b = b
z= Foo(2,3)
它给出了以下错误
TypeError: object.__new__() takes exactly one argument (the type to instantiate)
原文由 Danish Mahmood 发布,翻译遵循 CC BY-SA 4.0 许可协议
是正确的。但是, 您 有责任首先删除您的课程引入的参数,以便最终调用
object.__new__
时,*args
和**kwargs
都是空的。你的代码应该是这样的
此定义从 --- 中删除了您的新参数
a
和b
args
然后将其传递给 MRO 上的下一个人。同样适用于__init__
。