Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
424 views
in Technique[技术] by (71.8m points)

python - TypeError: object() takes no parameters after defining __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")

It is giving me the error:

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).

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!

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...