Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 instance with __new__(), or some other way?

like image 976
yasar Avatar asked Aug 29 '11 13:08

yasar


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.

like image 172
andronikus Avatar answered Nov 03 '22 06:11

andronikus


__init__ is called at the instanciation of an object

http://docs.python.org/reference/datamodel.html#object.__init__
like image 29
Intrepidd Avatar answered Nov 03 '22 06:11

Intrepidd