[Tutor] constructors

dman dman@dman.ddts.net
Tue, 9 Apr 2002 23:25:02 -0500


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?  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?

Constructors are much more essential in a language like C++ than they
are for Python.  In fact, a class in C++ _always_ has at least one
constructor, if you don't write it yourself the compiler will insert
it automatically.  In C++ you must statically specify all the members
that instances of the class will have.  In a ctor you initialze those
members to sensible values.  If you don't, you'll have garbage
(random) values in them.  (don't even try to consider what happens if
an exception is thrown from a ctor or dtor.  I've glanced over some
discussions before, and it is beyond me)  With python you have the
ability to create members after-the-fact, so it isn't such an issue.

I say use a ctor (called __init__ in python) if you need/want to
initialize the members of the object to some value when it is created.
If you don't need/want that, then don't bother writing an empty one.
I have found that most of the time you do want a ctor (though that
may be my C++/Java background there).  You can use default arguments
to allow for variations in usage.  For example :

class Person :
    def __init__( self , name="Not Specified" , age="Not Specified" ) :
        self.name = name
        self.age = age

p1 = Person()
p2 = Person( get_name_from_db() , get_age_from_db() )

-D

-- 

The fear of the Lord leads to life:
Then one rests content, untouched by trouble.
        Proverbs 19:23