mutually exclusive arguments to a constructor

Mel Wilson mwilson at the-wire.com
Fri Dec 30 16:08:51 EST 2011


Adam Funk wrote:

> (Warning: this question obviously reflects the fact that I am more
> accustomed to using Java than Python.)
> 
> Suppose I'm creating a class that represents a bearing or azimuth,
> created either from a string of traditional bearing notation
> ("N24d30mE") or from a number indicating the angle in degrees as
> usually measured in trigonometry (65.5, measured counter-clockwise
> from the x-axis).  The class will have methods to return the same
> bearing in various formats.
> 
> In Java, I would write two constructors, one taking a single String
> argument and one taking a single Double argument.  But in Python, a
> class can have only one __init__ method, although it can have a lot of
> optional arguments with default values.  What's the correct way to
> deal with a situation like the one I've outlined above?

Cleanest from the point of view of the class source code would be factory 
functions at the module level, or special classmethods to deal with the less 
common cases.  You see this a lot in wxPython when they have to deal with 
overloaded C++ constructors.

Most like the Java would be to check within __init__ for a string argument 
that could be parsed as a bearing, and failing that fall back to treating 
the argument as a numeric angle.

Neither fish nor fowl would be to accept named arguments for the different 
kinds of values.

	Mel.




More information about the Python-list mailing list