[Tutor] constructors

Alexandre Ratti alex@gabuzomeu.net
Wed, 10 Apr 2002 14:20:49 +0200


Hello,


At 07:35 10/04/2002 -0400, Erik Price wrote:
>>My understanding is that a constructor is useful to make sure that the 
>>object and its default values are initialised properly.
>
>Since Python is loosely/weakly/dynamically typed, does initializing really 
>matter a great deal?

I believe it makes your code simpler. If you do not initialise a class 
internal variable (is it called a "class member"?), you can't be sure it 
exists at all. Then you'll need to test its existence in every method where 
it is accessed. This may get messy when using many such variables.

>Or is it just to allow us to use polymorphism in a later method (by not 
>requiring that later method to specify a tuple over a list, for instance, 
>because a tuple has already been specified in the constructor, which makes 
>the later method more "general").

I'm not sure about polymorphism in this context. Maybe somebody can elaborate?

>>The __init__ constructor is executed when a class instance is created, 
>>hence you are sure it runs once (at least in "classic" classes; the rules 
>>may have changed for the new-type classes in Python 2.2).
>
>I am using 2.2 and probably won't need to use an older version.  But can 
>you tell me a bit more about "new-type classes"?  And how they're 
>different from "classic" classes?

I haven't used the new classes yet; I understand they allow you to subclass 
build-in types such as lists or dictionaries. There are other differences. 
See:

http://www.amk.ca/python/2.2/index.html#SECTION000310000000000000000


Cheers.

Alexandre