TypeError: object () does not accept parameters after defining __new__

I really don't understand where the error is in this small code:

#!/usr/bin/python3 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") 

This code presented above gives me an 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 
+6
source share
1 answer

In Python 3.3 and later, if you override both __new__ and __init__ , you need to avoid passing any additional arguments to the object methods that you override. If you just override one of these methods, this allows you to pass additional arguments to the other (since this usually happens without your help).

So, to fix your class, change the __new__ method as follows:

 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! 
+10
source

All Articles