类型错误:object() 在定义 __new__ 后不接受任何参数 [英] TypeError: object() takes no parameters after defining __new__

查看:59
本文介绍了类型错误:object() 在定义 __new__ 后不接受任何参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I really don't get where the error is in this little piece of code:

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 3.3 及更高版本中,如果您同时覆盖 __new____init__,则需要避免将任何额外的参数传递给您要覆盖的 object 方法.如果您只覆盖这些方法中的一个,则允许将额外的参数传递给另一个(因为这通常不需要您的帮助).

In Python 3.3 and later, if you're overriding both __new__ and __init__, you need to avoid passing any extra arguments to the object methods you're overriding. If you only override one of those methods, it's allowed to pass extra arguments to the other one (since that usually happens without your help).

因此,要修复您的类,请像这样更改 __new__ 方法:

So, to fix your class, change the __new__ method like so:

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!

这篇关于类型错误:object() 在定义 __new__ 后不接受任何参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆