Constructor overloading

Carl Banks imbosol at
Wed Jun 9 19:19:48 CEST 2004

Sergey Krushinsky <lunarium at> wrote in message news:<mailman.746.1086771964.6949.python-list at>...
> Hello all,
> Is there a common way to emulate constructor overloading in Python class?
> For instanse, I have 3 classes:
> 1/ Polar - to hold polar coordinates;
> 2/ Cartesian - to hold cartesian coordinates;
> 3/ Coordinates3D, which holds synchronized instances of the both in 
> __p__ and __c__ fields respectively.
> I want to design Coordinates3D so that when instantiated with Polar 
> argument, self.__p__=argument passed to constructor, and self.__c__ is 
> calculated. When argument is Cartesian, self.__c__=argument, and 
> self.__p__ is calculated. Runtime type checking works, but maybe there 
> is a better way?

Polar and Cartesian could both have methods cart() and polar().

x.cart() would return the cartesian representation whether x is
Cartesian, Polar, or the Coordinates3D.  If x is Polar, it makes the

x.polar() would do likewise returning polar representation.

Then, to initialize Coordinates3D, it could set _p and _c thusly:

    self._p = x.polar()
    self._c = x.cart()

This will work regardless of whether x is a Polar or Cartesian.  You
should define these methods for Coordinates3D, too.  (Note: you
shouldn't use variables of the form __xxx__ for regular variables; see
Naming Conventions at

OTOH, I could see why you might not want to do that.  If the point of
having three separate classes is so that you use a polar as a polar,
then maybe you wouldn't want to have it return a cartesian.  If that's
so, then just check the types.  It won't kill you.


More information about the Python-list mailing list