[英]Confused about calling a method within a class (PYTHON)
因此,我有一個用於處理溫度的類,它確實很基本,但是由於某種原因,將攝氏度轉換為華氏溫度無法正常工作時,無法在該類的某個區域返回正確的結果。
我正在寫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' )
我一生無法弄清為什么會這樣:(
您似乎誤讀了自己程序的輸出。 輸出的值是:
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,這是正確的。
我想,原因是整數運算。 嘗試((self.__magnitude - 32) * 5) / 9.0
和((self.__magnitude * 9) / 5.0) + 32
。 我執行了一個簡單的測試(沒有類的東西,只是數學),它給出了正確的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.