Can I have two init functions in a python class?

↘锁芯ラ 提交于 2019-12-04 05:39:34

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

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

An option is to use factory class methods:

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

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

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

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!