【问题标题】:TypeError: object() takes no parameters after defining __new__TypeError: object() 在定义 __new__ 后没有参数
【发布时间】:2020-05-28 18:11:24
【问题描述】:

我真的不明白这段代码的错误在哪里:

class Personne:
    def __init__(self, nom, prenom):
        print("Appel de la méthode __init__")
        self.nom = nom
        self.prenom = prenom

    def __new__(cls, nom, prenom):
        print("Appel de la méthode __new__ de la classe {}".format(cls))
        return object.__new__(cls, nom, prenom)

personne = Personne("Doe", "John")

它给了我错误:

Traceback (most recent call last):
  File "/home/bilal/Lien vers python/21_meta_classes/1_instanciation.py", line 21, in <module>
    personne = Personne("Doe", "John")
  File "/home/bilal/Lien vers python/21_meta_classes/1_instanciation.py", line 14, in __new__
    return object.__new__(cls, nom, prenom)
TypeError: object() takes no parameters

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    在 Python 3.3 及更高版本中,如果同时覆盖 __new____init__,则需要避免将任何额外参数传递给要覆盖的 object 方法。如果您只覆盖其中一种方法,则可以将额外的参数传递给另一种方法(因为这通常在没有您帮助的情况下发生)。

    因此,要修复您的课程,请更改 __new__ 方法,如下所示:

    def __new__(cls, nom, prenom):
        print("Appel de la méthode __new__ de la classe {}".format(cls))
        return object.__new__(cls) # don't pass extra arguments here!
    

    【讨论】:

    • FWIW,OP的代码实际上可以在Python3.2中运行,尽管错误确实发生在Python3.3+中
    • 谢谢兄弟,看来它正在工作。请告诉我,python 如何将其余参数传递给 init ,你能向我解释一下这个过程(如果你当然有时间的话)??!!
    • __init__ 的调用不是由object.__new__ 发出的,而是由type.__call__(绑定到类对象)发出的。所以object.__new__ 不需要看到您的__init__ 函数所期望的相同参数。
    • @Blckknght 你知道为什么它在 Python3.3+ 中是这样工作的吗?在某处有描述吗?我在文档中找不到此行为的描述?
    • 我想我现在有了答案。它隐藏在 typeobject.c 的注释中:github.com/python/cpython/blob/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-06
    • 1970-01-01
    • 1970-01-01
    • 2013-11-18
    • 1970-01-01
    相关资源
    最近更新 更多