[Tutor] constructors

alan.gauld@bt.com alan.gauld@bt.com
Wed, 10 Apr 2002 15:14:00 +0100


> On Tue, Apr 09, 2002 at 10:34:37PM -0400, Erik Price wrote:
> | When writing a class, is it recommended to always take advantage of 
> | constructors?  

> | and sometimes I use this class to pull an already-existing Person's 
> | attributes from a database table.  

This ties us back to the arlier comments about overridding.
In C++ and Delphi you can override constructors 
- unfortunately you can't do that in Python.
So you could have a non parameterised list that created a 
brand new 'empty' person. A parameterised one that created 
a full blown person and a third that took a personID that 
instantiated the person from the database. In C++/Java the 
constructors would all have the same name in Delphi you 
can give them different names because they are actually 
class methods. thus you would call:

P1 := Person.New	// no args, empty person

P2 := Person.Create('Alan','Gauld', 43, 'M', 8795)  // with attributes

P3 = Person.Read(OracleID, PersonID)  // from database with ID

Thuis constructors are still 'a good thing' provided you can write several
versions.

In Python we fake it with default params and key values:

class Person:
   def __init__(self, 
                name1='',name2='',age=0,sex='',phone=0,  #attributes
                dbID=0,PID=0)					   #
database
      if dbID: #get from DB
      elif name: # set attributes
      else: just zero everything


Now we can create persons with:

p = Person('Al','Gauld',44,'M',8795)

OR

p = Person(dbID = OracleID, PID = PersonID)

OR

p = Person()

But if you really don't have anything useful to do in the 
constructor then its not necessary. Never write code just
for the sake of it!

Alan G.