[Tutor] list.__init__ within class definition

Alan Gauld alan.gauld at btinternet.com
Thu Apr 21 10:50:05 CEST 2011


"Alex Companioni" <achompas at gmail.com> wrote 
> 
> class Tomato(list):
>    def __init__(self, data):
>        list.__init__(self, data)
> 
> The list.__init__ method (if it is a method, I'm not clear on what
> __init__ actually *is*) creates a list, right? 

Not quite.  __init__ (which is a method) is an initialiser not 
a constructor(*). The list is already created when you call 
init(). (Thats done by the __new__() class method)

> l = Tomato([1,2,3])
> 
> will create a list l with the values [1,2,3], correct?

Correct. But the creation of the list is done in the 
superclass __new__() not in the init. The assignment of 
the data to the list is done by __init__()


(*)Although init is not really a construxctir it is usually treated 
as one and often referred to as such by Python programmers. 
Indeed I do the same in my tutorial. But technically new() 
constructs the class, init initialises it.
<Aside nature=off-topic> 
This is similar to Objective C which also has separate 
constructor/initialiser functions namely alloc and init. So you 
can create an ObjC object like

myObj = [ [MyClass alloc] init ]

But this is such a common combination that ObjC provides 
the wrapper new:

myObj = [MyClass new]

Which is how ObjC programmer create classes 99% of the time!
</Aside>

HTH

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list