Adam Funk <a24...@ducksburg.com> wrote: >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?
You can determine the type of the input data by using isinstance() and take the appropriate actions depending on this decision: >>> class MyClass(object): ... def __init__(self, input_data): ... if isinstance(input_data, basestring): ... print "Do actions for string type input" ... elif isinstance(input_data, float): ... print "Do actions for float type input" ... def get_output_data(self): ... return "output data" ... >>> a = MyClass("String") Do actions for string type input >>> b = MyClass(15.9) Do actions for float type input Best regards, Günther -- http://mail.python.org/mailman/listinfo/python-list