[英]Class method doesn't return anything
我在調用(訪問?)類中的方法時遇到問題
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__()
嘗試打印returnmax
, returnmin
, returnavg
return的值時, returnmax
不打印任何內容。 僅使用print語句(如str方法中的方法)似乎有效,為什么呢?
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)
str(obj)
將調用def __str__(self)
函數,因此str函數需要返回一個值,而不是輸出一個值
當函數返回值但您忘記打印時,看不到它
與shell不同
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.