25

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
0

1 Answer 1

42

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!
Sign up to request clarification or add additional context in comments.

5 Comments

FWIW, the OP's code actually works in Python3.2, though the error indeed occurs in Python3.3+
Thanks bro, it seems that it is working. please, tell me, how does python pass the rest of the arguments to init , can you explain the process to me (if you have time of course) ??!!
The call to __init__ isn't made by object.__new__, but rather by type.__call__ (bound to the class object). So object.__new__ doesn't need to see the same arguments that your __init__ function expects.
@Blckknght do you know why it works that way in Python3.3+? Is it described somewhere? I could not find description of this behavior in the doc?
I think I've an answer now. It's hidden in comment in typeobject.c: github.com/python/cpython/blob/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.