【问题标题】:Confused about calling a method within a class (PYTHON)对在类中调用方法感到困惑(PYTHON)
【发布时间】:2014-06-06 05:16:42
【问题描述】:

所以我有一个处理温度的课程,它真的很基础,但由于某种原因,当它在其他情况下工作时,将摄氏度转换为华氏度无法在课程的一个区域返回正确的结果。

我正在写add方法,为了将两个不同类型的温度相加,它们必须进行转换。我有一种在摄氏度和华氏度之间切换的方法,当我在测试程序中这样做时它就可以工作:

Testing celsius method:
Converting to celsius...
Result: Temperature: -12.222222222222221 degrees C

Testing fahrenheit method:
Converting back to fahrenheit...
Result: Temperature: 10.0 degrees F

但是,如果我尝试使用它来添加两种不同的类型(额外打印以查看它在做什么):

def __add__( self, other ):

    if type( other ) != Temperature:
        other = Temperature( other )

    a_scale = self.__scale

    if a_scale == 'F':
        print(self)
        print(other)
        temp_1 = self.fahrenheit()
        temp_2 = other.fahrenheit()
        print(temp_1)
        print(temp_2)
        temp_3 = temp_1.__magnitude + temp_2.__magnitude
        return Temperature( temp_3, 'F' )

    elif a_scale == 'C':
        print(self)
        print(other)
        temp_1 = self.celsius()
        temp_2 = other.celsius()
        print(temp_1)
        print(temp_2)
        temp_3 = temp_1.__magnitude + temp_2.__magnitude
        return Temperature( temp_3, 'C')

它将打印出它已将 10 摄氏度转换为 68 华氏度 (???)

输出:

Testing addition
Temp 2 = Temperature: 20 degrees C
Performing temp1 + temp2...
Temperature: 10 degrees F
Temperature: 20 degrees C
Temperature: 10 degrees F
Temperature: 68.0 degrees F
Temperature: 78.0 degrees F

这是华氏法:

def fahrenheit( self ):

    if self.__scale == 'F':
        return Temperature( self.__magnitude, 'F')
    elif self.__scale == 'C':
        f = ((self.__magnitude * 9) / 5) + 32
        return Temperature( f, 'F' )

据我所知,它工作得非常好。

摄氏度,几乎相同:

def celsius( self ):

    if self.__scale == 'C':
        return Temperature( self.__magnitude, 'C')
    elif self.__scale == 'F':
        c = ((self.__magnitude - 32) * 5) / 9
        return Temperature( c, 'C' )

我一辈子都想不通为什么会这样:(

【问题讨论】:

    标签: python class methods return add


    【解决方案1】:

    您似乎误读了自己程序的输出。输出的值为:

    Temperature: 10 degrees F    # self
    Temperature: 20 degrees C    # other
    Temperature: 10 degrees F    # temp_1 = self.fahrenheit()
    Temperature: 68.0 degrees F  # temp_2 = other.fahrenheit()
    Temperature: 78.0 degrees F  # The sum of the above two
    

    因此,10°F 变为 10°F,20°C 变为 68°F,这是正确的。

    【讨论】:

      【解决方案2】:

      我猜,原因是整数算术。试试((self.__magnitude - 32) * 5) / 9.0((self.__magnitude * 9) / 5.0) + 32。我进行了一个简单的测试(没有课,只有数学),它给出了正确的结果。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-17
        • 2013-07-27
        • 1970-01-01
        • 2017-03-20
        • 2013-07-19
        • 1970-01-01
        • 2020-04-19
        相关资源
        最近更新 更多