Class design issues: multiple constructors

Alex Martelli aleax at aleax.it
Thu Aug 7 07:00:02 EDT 2003


Greg Brunet wrote:
   ...
> instance.  When I first started, I included a filename as a parameter
> that would be used to open an existing DBF file.  Next I decided to add
> the ability to create a new DBF file.  This method needs additional
> parameters (such as the field definitions), and, while in some other
> languages, I could provide 2 versions of the constructor (overload it if
> I'm using the right terminology), and the compiler would use the
> appropriate one, things don't seem to work that way in Python.  I'm also
> thinking that I might rather name the methods more specifically (such as
> Open & Create) instead of both being __init__.  What would be the

Right.  The Pythonic way is to provide "factory functions" that prepare
and return the object you need.  Cosmetically, you may make the factory
functions part of the class itself, using the staticmethod and classmethod
built-in types of Python 2.2 and later -- no real need, but some people
are very keen on this style, so Python now supports it.

> Pythonic way to go about doing this?  Would I make an __init__, Open, &
> Create methods, and make 2 calls for each DBF object, like this:
> 
> class dbf:
>     __init__(self):
>         pass
>     Create(self, filename, fieldDefs):
>         pass
>     Open(self, filename):
>         pass

No, it should rather be something like:

class dbf(object):
    # no need to define __init__ if it's empty!
    def Create(filename, fieldDefs):
        result = dbf()
        # use filename and fieldDefs to populate 'result' appropriately
        return result
    Create = staticmethod(Create)
    def Open(filename):
        result = dbf()
        # use filename to populate 'result' appropriately
        return result
    Open = staticmethod(Open)


> # open existing file
> f1 = dbf()
> f1 = dbf.Open('customer.dbf')

No, this wouldn't work with the code you propose; it would with
the variant I suggest, but the first of these statements is useless
so you should remove it.

> # create a new file
> f2 = dbf()
> f2 = dbf.Create('states.dbf',  [('StateCode', 'C', 2), \
>     ('StateName','C',20)]

Ditto.


Alex





More information about the Python-list mailing list