Can I have two init functions in a python class?

I would just include a boolean in your init method. Instead of having two __init__ methods, do the following:

class geoLocation:
    def __init__(self, lat, long, degrees=True):
        if degrees:
            # process as fromDegrees
            (self._radLat, self._radLong, self._degLat, self._degLong) = self.fromDegrees(lat, long)
        else:
            (self._radLat, self._radLong, self._degLat, self._degLong) = self.fromRadians(lat, long)

    def fromDegrees(self, lat, long):
        # some function returning radLat and long and degLat and long in a tuple
    def fromRadians(self, lat, long):
        # same idea but different calculations

Another option is to have to subclasses of GeoLocation, say DegreesGeoLocation and RadiansGeoLocation. Now you can give each their own init function.

You are now storing the location twice in your class, once using radians and once using degrees. This can cause problems if you accidentally modify one representation but forget the other. I think you could best use one representation, and provide getters and setters which eventually do the conversion to the other representation.


An option is to use factory class methods:

class geoLocation(object):
    @classmethod
    def fromDegrees(cls, lat, long):
        return cls(lat, long, True)

    @classmethod
    def fromRadians(cls, lat, long):
        return cls(lat, long, False)

    def __init__(self, lat, long, degrees=True):
        if degrees:
            #blah
        else:
            #blah

Chose one default ( radians or degrees ) and stick with it. You can write a classmethod to automatically convert to the other:

class geoLocation:
    def __init__(self, lat, long):
        """init class from lat,long as radians"""

    @classmethod
    def fromDegrees(cls, dlat, dlong):
        """creat `cls` from lat,long in degrees """
        return cls( to_radians(dlat), to_radians(dlong))

    @classmethod
    def fromRadians(cls, lat, long): # just in case
        return cls(lat, long)

obj = geoLocation.fromDegrees(10,20) # returns a new geoLocation object

Tags:

Python

Init