Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: object() takes no parameters after defining __new__

Tags:

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 
like image 881
Sidahmed Avatar asked Jan 13 '16 21:01

Sidahmed


People also ask

What is the correct syntax for defining an __ Init__ method that takes no parameters?

The “TypeError: object() takes no arguments” error is raised when you do not declare a method called __init__ in a class that accepts arguments. To solve this error, double-check your code to ensure that __init__() is spelled correctly. The method should have two underscores on either side of the word “init”.

Why does my class take no arguments?

The Python "TypeError: Class() takes no arguments" occurs when we forget to define an __init__() method in a class but provide arguments when instantiating it. To solve the error, make sure to define the __init__() (two underscores on each side) method in the class.

Which is the definition of function called if it does nothing and takes no arguments in python?

The first Main.generate_noise() function definition that you give (the one without arguments) references the self variable.

What is meant by init method without parameters?

__init__ Method with No Parameter__init__ method can be used with no parameter. In this case, the values of the instance will be set to the default values or nothing will be done.


Video Answer


1 Answers

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! 
like image 185
Blckknght Avatar answered Oct 12 '22 06:10

Blckknght