Why does __init__ not get called if __new__ called with no args
I am trying to create (not exactly restore) an object which has its attributes saved in a database. Therefore, I do not want to call __init__
. This desire appears to be inline with Guido's intended use for __new__
. I do not understand why __init__
is not getting called.
Take the following snippet for example, it returns an instance of class User 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 the python docs __init__
is supposed to be called when __new__
"returns an instance of cls."
So why is __init__
not being even called, even though __new__
returns a class instance?
The constructor (User()
) is responsible for calling the allocator (User.__new__()
) and the initializer (User.__init__()
) in turn. Since the constructor is never invoked, the initializer is never called.
Because you're bypassing the usual construction mechanism, by calling __new__
directly. The __init__
-after-__new__
logic is in type.__call__
(in CPython see typeobject.c
, type_call
function), so it happens only when you'd do User(...)
.
精彩评论