Why __init__ is not called if __new__ is called without arguments

I am trying to create (not accurately restore) an object that has its attributes stored in the database. Therefore, I do not want to call __init__ . This desire seems to be built-in with the intended use of Guido for __new__ . I do not understand why __init__ not being called.

Take the following snippet, for example, it returns an instance of the User class without calling __init__ .

 class User(object): def __init__(self, arg1, arg2): raise Exception user = User.__new__(User) print user <project.models.User object at 0x9e2dfac> 

This is the exact behavior I want. However, my question is that I do not understand why?

According to python, docs __init__ supposed to be called when __new__ "returns an instance of cls."

So why __init__ not even called even though __new__ returns an instance of the class?

+7
python
source share
2 answers

Constructor ( User() ) is responsible for calling the dispenser ( User.__new__() ) and the initializer ( User.__init__() ) in the queue. Because the constructor is never called, the initializer is never called.

+10
source share

Because you bypass the usual build mechanism by calling __new__ directly. The logic __init__ -after- __new__ is in type.__call__ (in CPython see the function typeobject.c , type_call ), so this only happens when you do User(...) .

+10
source share

All Articles