__init__ explanation please

Neil Cerutti mr.cerutti at gmail.com
Mon Jan 14 13:43:47 EST 2008


On Jan 14, 2008 12:08 PM, Reedick, Andrew <jr9445 at att.com> wrote:
> > -----Original Message-----
> > From: python-list-bounces+jr9445=att.com at python.org [mailto:python-
> > list-bounces+jr9445=att.com at python.org] On Behalf Of Hrvoje Niksic
> > Sent: Monday, January 14, 2008 11:29 AM
> > Only if by "construct" you mean "allocate".  __init__ starts out with
> > an empty object and brings it to a valid state, therefore
> > "constructing" the object you end up with.  That operation is exactly
> > what other languages call a constructor.
>
> Nah.  Most other languages combine the constructor and an init function.
> Normally with c++ I'll have the constructor call an Init() function so I
> can re-initialize the object as needed.  Python has explicitly split the
> two.

> Besides, the Python docs say that __new__ is the constructor and
> __init__ may or may not be called after the instance is created:

The documentation of __new__ carefully refrains from calling __new__ a
constructor. Both __new__ and __init__ mention the object constructor
expression, e.g., "list()".

> __init__( self[, ...])
>         Called when the instance is created.
>         ...
>         As a special constraint on constructors, no value may be
> returned;

Once again, the documentation is referring to constructor expressions.
As you noted, __init__ may return a value when not called by a
constructor expression.

C++'s constructor initialization lists are the closest thing to
Python's __new__. They can perform tasks for which Python might need
__new__. For example, a class member that's a reference must be
initialized in the initialization list, because it cannot be set once
the body of the constructor begins.

-- 
Neil Cerutti <mr.cerutti+python at gmail.com>



More information about the Python-list mailing list