Exercism: Space Age (Python)

根据地球上的时间,来计算其他星球上的时间。开始为每一个星球写了一个方法。后来看了别人的答案,发现可以用setattr来动态添加方法。


原版:

EARTH_YEAR_RATIO = {
"Mercury": 0.2408467,
"Venus": 0.61519726,
"Mars": 1.8808158,
"Jupiter": 11.862615,
"Saturn": 29.447498,
"Uranus": 84.016846,
"Neptune": 164.79132
}
class SpaceAge:
    def __init__(self, seconds):
        self.__earth_year = seconds / 31557600.0
    def on_earth(self):
        return round(self.__earth_year,2)
    def on_mercury(self):
        return round(self.__earth_year / EARTH_YEAR_RATIO["Mercury"], 2)
    def on_venus(self):
        return round(self.__earth_year / EARTH_YEAR_RATIO["Venus"], 2)
    
    def on_mars(self):
        return round(self.__earth_year / EARTH_YEAR_RATIO["Mars"], 2)
    def on_jupiter(self):
        return round(self.__earth_year / EARTH_YEAR_RATIO["Jupiter"], 2)
    def on_saturn(self):
        return round(self.__earth_year / EARTH_YEAR_RATIO["Saturn"], 2)
        
    def on_uranus(self):
        return round(self.__earth_year / EARTH_YEAR_RATIO["Uranus"], 2)
        
    def on_neptune(self):
        return round(self.__earth_year / EARTH_YEAR_RATIO["Neptune"], 2)

优化本:

from functools import partial
EARTH_YEAR_RATIO = {
"Earth": 1.0,
"Mercury": 0.2408467,
"Venus": 0.61519726,
"Mars": 1.8808158,
"Jupiter": 11.862615,
"Saturn": 29.447498,
"Uranus": 84.016846,
"Neptune": 164.79132
}
class SpaceAge:
    def __init__(self, seconds):
        self.__earth_year = seconds / 31557600.0
        self.gen_method()
    def gen_method(self):
        compute = lambda r : round(self.__earth_year / r, 2) 
        for planet, ratio in EARTH_YEAR_RATIO.items():
            self.__setattr__(f"on_{planet.lower()}", partial(compute,ratio))

评论

此博客中的热门博文

拜厄练习曲44, 45

拜厄练习曲38, 39