__init__ explanation please

Ben Finney bignose+hates-spam at benfinney.id.au
Sun Jan 13 07:58:29 EST 2008


Jeroen Ruigrok van der Werven <asmodai at in-nomine.org> writes:

> -On [20080113 01:41], Erik Lind (elind at spamcop.net) wrote:
> >I'm new to Python, and OOP. I've read most of Mark Lutz's book and
> >more online and can write simple modules, but I still don't get
> >when __init__ needs to be used as opposed to creating a class
> >instance by assignment.
> 
> I personally tend to see __init__ or __new__ as equivalent to what
> other languages call a constructor.

That's getting the two of them confused. __new__ is a constructor,
__init__ is not.

> (And I am sure some people might disagree with that. ;))

It isn't really a matter for much debate.

    <URL:http://www.python.org/doc/ref/customization.html>

__new__ is the constructor: it creates the instance and returns it.

Along the way, it calls __init__ on the *already-created* instance, to
ask it to initialise itself ready for use. So, __init__ is an
"initialiser" for the instance.

Python, unlike many other OO languages, fortunately has these two
areas of functionality separate. It's far more common to need to
customise instance initialisation than to customise creation of the
instance. I override __init__ for just about every class I write; I
can count the number of times I've needed to override __new__ on the
fingers of one foot.

-- 
 \      "Reichel's Law: A body on vacation tends to remain on vacation |
  `\         unless acted upon by an outside force."  -- Carol Reichel |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list