[Tutor] constructors

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


Hi Erik,


At 22:50 09/04/2002 -0400, you wrote:
>Date: Tue, 9 Apr 2002 22:34:37 -0400
>From: Erik Price <erikprice@mac.com>
>Subject: [Tutor] constructors
>
>When writing a class, is it recommended to always take advantage of
>constructors?  I have written a class called Person, which helps me to
>organize my user-input error-checking (by confining error-checking
>functions to the methods that set instance attributes).  I don't have a
>constructor, because sometimes I use this class to build a new Person
>and sometimes I use this class to pull an already-existing Person's
>attributes from a database table.  But constructors are seen as a
>"really good thing", but as far as I can see a constructor is just a
>shortcut.  Please share your thoughts on using constructors, if you
>would?

My understanding is that a constructor is useful to make sure that the 
object and its default values are initialised properly.

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).

Example:

class Foo:
         """Just a silly class."""

         def __init__(self):
                 """Initialise the class."""
                 theList = []

         def addBar(self, bar):
                 """Store bar."""
                 # Here you do not need to test if theList exists.
                 theList.append(bar)


Cheers.

Alexandre