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?
-
1You can take a look here: rafekettler.com/magicmethods.html But in general new called first while init usually called right after instance created.Artsiom Rudzenka– Artsiom Rudzenka2011-08-29 13:27:22 +00:00Commented Aug 29, 2011 at 13:27
Add a comment
|
2 Answers
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.
5 Comments
Karl Knechtel
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.andronikus
True indeed! Although this should be used with all due caution, as with most of Python's method overloading.
Eli Collins
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.agf
You should really edit this.
__new__ doesn't call __init__ as the docs and @Karl say, it's called automatically under certain circumstances.Eli Collins
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.