setattr(x,y,lambda:...)的奇怪行为

时间:2014-09-29 13:58:00

标签: python python-2.7 math lambda setattr

运行以下代码时,我得到以下输出:

31.688087814
131.569532877

此输出由我在下面标出的两条线产生。值应该相同(据我所知),并且都应该具有第一个值。我无法弄清楚值被转换为第二个值的位置。这是来自site exercise.io的练习。我是为自己的“娱乐”而做的。但这让我很难过。任何帮助都非常赞赏。

#!/usr/bin/env python

"""
Earth:   orbital period 365.25 Earth days, or 31557600 seconds
Mercury: orbital period 0.2408467 Earth years
Venus:   orbital period 0.61519726 Earth years
Mars:    orbital period 1.8808158 Earth years
Jupiter: orbital period 11.862615 Earth years
Saturn:  orbital period 29.447498 Earth years
Uranus:  orbital period 84.016846 Earth years
Neptune: orbital period 164.79132 Earth years
"""

PLANETS = {
    "on_earth": 31557600.0,
    "on_mercury": 31557600.0 * 0.2408467,
    "on_venus": 31557600.0 * 0.61519726,
    "on_mars": 31557600.0 * 1.8808158,
    "on_jupiter": 31557600.0 * 11.862615,
    "on_saturn": 31557600.0 * 29.447498,
    "on_uranus": 31557600.0 * 84.016846,
    "on_neptune": 31557600.0 * 164.79132
}

class SpaceAge(object):

    def __init__(self, seconds):
        self.seconds = seconds

        if not isinstance(seconds, (int, long, float)):
            raise ValueError("Invalid input type {}".format(type(seconds)))

        for k, v in PLANETS.iteritems():
            func = lambda : seconds / v
            if k == "on_earth":
                print func()                # <<*** first output value 
            setattr(self, k, func)

if __name__ == "__main__":
    age = SpaceAge(1e9)
    print age.on_earth()                    # <<*** second output value

0 个答案:

没有答案