Constructor overloading

Shalabh Chaturvedi shalabh at cafepy.com
Wed Jun 9 23:36:42 EDT 2004


Sergey Krushinsky wrote:

> 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?
> 
> Thanks in advance,
> Sergey

My usual approach to such cases is using keyword arguments:

#untested code

class Coordinates3d:
     def __init__(self, polar_coords=None, cartesian_coords=None):
         if polar_coords:
             ....
         elif cartesian_coords:
             ....
         else:
             raise Exception, 'at least one required'

Then it can be instantiated as Coordinates3d(polar_coords=polar) or 
Coordinates3d(cartesian_coords=cartes). You can also add a check if 
polar_coords and cartesian_coords then raise an exception 'only one 
should be specified'.

Another option is to define two staticmethods on the class which can be 
used thus:

a = Coordinates3d.from_polar(polar)
b = Coordinates3d.from_cartes(cartes)

Both options are explicit, which I think is a Good Thing. Depends on 
your taste.

--
Shalabh





More information about the Python-list mailing list