[Tutor] __init__

Alan Gauld alan.gauld at yahoo.co.uk
Tue Aug 30 16:37:44 EDT 2016


On 30/08/16 17:59, monikajg at netzero.net wrote:

> Assume you have a child class with no init, but it has empty,
 > default __init__ provided by pathon

It inherits the empty init from object.

>  and the same for its parent class. When instantiating child class,
 > child class's __new__ calls its ___init__ in child class and then
 > calls __init__ in parent class?

Usually there is only one new in object.

When new finishes constructing the empty object
init() gets called. There is no magic it is just a standard
method call that starts at the lowest level child and works
its way up the tree until it finds an init. If all else
fails it reaches the top level object.init()

If any subclass has defined an init it will be called first
and unless it calls super() it will be the last.

> Why does it not just use the default, provided by python
 > __init__ since it found it?

It uses the first init it finds. The last place it looks is
in object which has an empty init method. Python itself does
not provide a default init, it is the empty one in object
that fulfills that function (since every class ultimately
inherits object).

I suspect that's how Java does it too since every Java
class descends from Object. But I've not examined Java
that closely.

As eryksun has intimated there is actually another layer
of magic involved in Python via the metaclass mechanism
which allows us to change the mechanism by which classes
are constructed. but that is way deeper than most
programmers ever need to go! Remember the old adage
  -Keep it Simple!

Alan G



More information about the Tutor mailing list