What method calls `__init__()` in Python classes
I was wondering how __init__()
methods get called. Does __new__()
calls it, or __call__()
calls it after it created an instanc开发者_运维百科e with __new__()
, or some other way?
Python determines whether __new__() should call __init__():
If __new__() returns an instance of cls, then the new instance’s __init__() method will be invoked like __init__(self[, ...]), where self is the new instance and the remaining arguments are the same as were passed to __new__().
__init__() will not be called if __new__() is overridden and does not return an instance of the class.
__call__() is invoked when an instance object is called like a function:
class MyObj:
def __call__():
print 'Called!'
>>> mo = MyObj()
>>> mo()
Called!
And of course you can define __call__() with whatever arguments and logic you want.
__init__
is called at the instanciation of an object
http://docs.python.org/reference/datamodel.html#object.__init__
精彩评论