2014-02-26 41 views
0

我有打電話的問題(訪問?)在我的類中的方法類的方法不返回任何

class dag(object): 

    def __init__(self,temp): 
     self.name = temp[3] 
     self.l_o_t = temp 

    def __str__(self): 

     print ("The hottest temperature was:",self.l_o_t[0]) 
     print ("The coolest temperature was:",self.l_o_t[1]) 
     print ("The average temperature was:",self.l_o_t[2]) 

    def returnmax(self): 

     return self.l_o_t[0] 
    def returnmin(self): 
     return self.l_o_t[1] 
    def returnavg(self): 
     return self.l_o_t[2] 


def main(): 
    temp = dag(list_of_temperatures) 
    temp.returnmax() 
    temp.returnmin() 
    temp.returnavg() 
    temp.__str__() 

當試圖打印出值returnmaxreturnminreturnavg返回主程序沒有按不打印任何東西。只有打印報表,如str方法似乎工作,爲什麼?

回答

4

Python交互式解釋器爲您提供了一切,因爲它是一個交互式調試器,但在Python程序中您需要明確打印值。

添加print()來電顯示的返回值:

temp = dag(list_of_temperatures) 
print(temp.returnmax()) 
print(temp.returnmin()) 
print(temp.returnavg()) 

通常情況下,一個__str__方法將返回一個字符串值,使用print()的方法:

def __str__(self): 
    value = (
     'The hottest temperature was: {0.l_o_t[0]}\n' 
     'The coolest temperature was: {0.l_o_t[1]}\n' 
     'The average temperature was: {0.l_o_t[2]}\n' 
    ).format(self) 
    return value 

,然後你'使用print(),這將調用str()的值,這又調用__str__()方法:

print(temp) 
+0

這對常規功能來說是不一樣的嗎?在那裏你不必使用print來調用函數值? – user3221453

+0

@ user3221453:* Anywhere *你想要產生輸出到你需要顯式使用'print()'的終端。 –

+0

謝謝。關於您對__str__方法所做的修改,.format(self)會生成以下錯誤: IndexError:元組索引超出範圍 – user3221453

1

str(obj)將調用def __str__(self)功能,所以STR功能需要返回一個值,而不是打印值

當函數返回一個值,但你忘了打印,你看不到它

它與外殼不一樣

class dag(object): 

    def __init__(self,temp): 
     self.name = temp[3] 
     self.l_o_t = temp 

    def __str__(self): 
     a = "The hottest temperature was:%s"%self.l_o_t[0] 
     b = "The coolest temperature was:%s"%self.l_o_t[1] 
     c = "The average temperature was:%s"%self.l_o_t[2] 
     return '\n'.join([a,b,c]) 

    def returnmax(self): 
     return self.l_o_t[0] 
    def returnmin(self): 
     return self.l_o_t[1] 
    def returnavg(self): 
     return self.l_o_t[2] 


def main(): 
    temp = dag([27,19,23,'DAG']) 
    print(temp.returnmax()) 
    print(temp.returnmin()) 
    print(temp.returnavg()) 
    print(temp) # print will call str, that is __str__ 


if __name__ == '__main__': 
    main() 
+0

如果你解釋你做了什麼,你的答案會更好。讀者很難逐行嘗試看看你做了什麼不同的事情。 –

+0

感謝您的建議,Bryan Oakley! – WeizhongTu