__init__ is the initialiser
timothy.c.delaney at gmail.com
Mon Feb 3 01:02:17 CET 2014
On 1 February 2014 14:42, Steven D'Aprano <
steve+comp.lang.python at pearwood.info> wrote:
> On Fri, 31 Jan 2014 14:52:15 -0500, Ned Batchelder wrote:
> (In hindsight, it was probably a mistake for Python to define two create-
> an-object methods, although I expect it was deemed necessary for
> historical reasons. Most other languages make do with a single method,
> Objective-C being an exception with "alloc" and "init" methods.)
I disagree. In nearly every language I've used which only has single-phase
construction, I've wished for two-phase construction. By the time you get
to __init__ you know the following things about the instance:
1. It is a complete instance of the subclass - there's no part of the
structure that is invalid to access (of course, many attributes might not
2. Calling a method from __init__ will call the subclass' method. This
allows subclasses to hook into the initisation process by overriding
methods (of course, the subclass will need to ensure it has initialised all
the state it needs). This is generally not allowed in languages with
single-phase construction because the object is in an intermediate state.
For example, in C++ the vtable is for the class currently being
constructed, not the subclass, so it will always call the current class'
implementation of the method.
In Java you can actually call the subclass' implementation, but in that
case it will call the subclass method before the subclass constructor is
actually run, meaning that instance variables will have their default
values (null for objects). When the base class constructor is eventually
run the instance variables will be assigned the values in the class
definition (replacing anything set by the subclass method call).
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-list