12

I was wondering how __init__() methods get called. Does __new__() calls it, or __call__() calls it after it created an instance with __new__(), or some other way?

1
  • 1
    You can take a look here: rafekettler.com/magicmethods.html But in general new called first while init usually called right after instance created. Commented Aug 29, 2011 at 13:27

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

5 Comments

More accurately, it's called implicitly by the Python runtime. You can write your own __new__ that doesn't call __init__ and it will still be called as long as you return an instance of the class.
True indeed! Although this should be used with all due caution, as with most of Python's method overloading.
An important thing to note... Pythnon's runtime will call __init__ whenever __new__ returns an instance of cls, even if it's already been initialized (eg, is being returned from a cache); and it won't call __init__ of any kind if the return value isn't an instance of cls.
You should really edit this. __new__ doesn't call __init__ as the docs and @Karl say, it's called automatically under certain circumstances.
Also, just wanted to note... the __call__ that @yasar was probably referring to (though he didn't know it) is the __call__ method of the metaclass, in this case type, of which MyObj is an instance. That's the one that gets called when you do MyObj(), and is what contains this logic.
3

__init__ is called at the instanciation of an object

http://docs.python.org/reference/datamodel.html#object.__init__

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.