__init__ function problem

Duncan Booth duncan.booth at invalid.invalid
Tue Nov 7 15:02:30 CET 2006


"kelin,zzf818 at gmail.com" <zzf818 at gmail.com> wrote:

> Today I read the following sentences, but I can not understand what
> does the __init__ method of a class do?
> __init__ is called immediately after an instance of the class is
> created. It would be tempting but incorrect to call this the
> constructor of the class. It's tempting, because it looks like a
> constructor (by convention, __init__ is the first method defined for
> the class), acts like one (it's the first piece of code executed in a
> newly created instance of the class), and even sounds like one ("init"
> certainly suggests a constructor−ish nature). Incorrect, because the
> object has already been constructed by the time __init__ is called, and
> you already have a valid reference to the new instance of the class.
> But __init__ is the closest thing you're going to get to a constructor
> in Python, and it fills much the same role.

I don't know where you read that, but it is wrong (or at least out of 
date). The closest thing you are going to get to a constructor in Python is 
actually the constructor '__new__'. Mostly though you don't need to worry 
about __new__ in Python.

> 
> It says the __init__ is called immediately after an instance of the
> class is created. What dose "immediately" mean?

It means that when you call:

x = SomeClass()

the interpreter first calls the constructor SomeClass.__new__, and then 
immediately calls the initialiser SomeClass.__init__ on the newly created 
object, and after that it returns the newly created object.

A constructor creates an object and returns it, an initialiser initialises 
an existing object and does not return anything.

The constructor has the power to control how the memory for the object is 
allocated (e.g. in Python it could return an already existing object 
instead of creating a new one, but in that case the initialiser will be 
called again on the existing object).

The initialiser usually sets up the attributes on a newly created object, 
but for immutable objects (e.g. tuple) the attributes must be set by the 
constructor.



More information about the Python-list mailing list