gpt4 book ai didi

python - TypeError 对象没有参数

转载 作者:太空宇宙 更新时间:2023-11-04 05:16:24 25 4
gpt4 key购买 nike

我只是想编写一段代码,说明如何使用 super__new__。这是代码:

class Person(object):
def __new__(cls, name, age):
print('__new__called')
return super(Person, cls).__new__(cls, name, age)
def __init__(self, name, age):
print('__init__called')
self.name = name
self.age = age
def __str__(self):
return('<Person:%s(%s)>'%(self.name, self.age))
if __name__ == '__main__':
piglei = Person("piglei", 24)
print(piglei)

Python 引发了一个 TypeError 并说明了第 4 行,object() 没有参数

最佳答案

object.__new__ 不接受任何参数。您在 __new__ 中的 super 调用将失败:

return super(Person, cls).__new__(cls, name, age)

因为您还将 nameage 传递给 object.__new__

您不需要将它们传递给 object;要么一起删除 __new__ 定义,要么不向它传递任何参数:

return super(Person, cls).__new__(cls)

无论哪种方式,真的没有理由在这里使用 __new__ 但我猜你正在试验。如果你是,请注意你也可以在 super 中删除 Personcls 并使用它的零参数形式,即:

return super().__new__(cls)

关于python - TypeError 对象没有参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41606555/

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