Python 3.x 温度转换,无需调用方法
我正在寻找一种打印t1的解决方案,转换成kelvins,而不调用下面的任何方法。关于t1是如何创建的以及打印输出的解决方案,请参见底部。我希望很快能听到一些反馈Python 3.x 温度转换,无需调用方法,python-3.x,class,oop,methods,printing,Python 3.x,Class,Oop,Methods,Printing,我正在寻找一种打印t1的解决方案,转换成kelvins,而不调用下面的任何方法。关于t1是如何创建的以及打印输出的解决方案,请参见底部。我希望很快能听到一些反馈 class Temperature: # --- YOUR CODE STARTS HERE val = 0 def __init__(self,val, unit): self.val = val self.unit = unit def celcius(self)
class Temperature:
# --- YOUR CODE STARTS HERE
val = 0
def __init__(self,val, unit):
self.val = val
self.unit = unit
def celcius(self):
if self.unit == "F":
new_temp = (self.val - 32)*(5/9)
self.unit = "F"
new_unit = self.unit
return round(new_temp,2), new_unit
elif self.unit == "K":
new_temp = self.val - 273.15
self.unit = "F"
new_unit = self.unit
return round(new_temp,2), new_unit
else:
return round(self.val,2), self.unit
def fahrenheit(self):
if self.unit == "C":
new_temp = (self.val * (9/5)) + 32
self.unit = "F"
new_unit = self.unit
return round(new_temp,2), new_unit
elif self.unit == "K":
new_temp = (val - 273.15) * (9/5) + 32
self.unit = "F"
new_unit = self.unit
return round(new_temp,2), new_unit
else:
return round(self.val,2), self.unit
def kelvin(self):
if self.unit == "F":
new_temp = (self.val - 32)*(5/9) + 273.15
self.unit = "K"
new_unit = self.unit
return round(new_temp,2), new_unit
elif self.unit == "C":
new_temp = self.val + 273.15
self.unit = "K"
new_unit = self.unit
return round(new_temp,2), new_unit
else:
return round(self.val,2), self.unit
def __str__(self):
t1 = Temperature(31, "F")
print(t1)
问题是打印t1以获得272.59 K的结果。以下是我可以做的,以满足您的要求:
class Temperature:
# --- YOUR CODE STARTS HERE
val = 0
def __init__(self,val, unit):
self.val = val
self.unit = unit
def celcius(self):
if self.unit == "F":
new_temp = (self.val - 32)*(5/9)
self.unit = "F"
new_unit = self.unit
return round(new_temp,2), new_unit
elif self.unit == "K":
new_temp = self.val - 273.15
self.unit = "F"
new_unit = self.unit
return round(new_temp,2), new_unit
else:
return round(self.val,2), self.unit
def fahrenheit(self):
if self.unit == "C":
new_temp = (self.val * (9/5)) + 32
self.unit = "F"
new_unit = self.unit
return round(new_temp,2), new_unit
elif self.unit == "K":
new_temp = (val - 273.15) * (9/5) + 32
self.unit = "F"
new_unit = self.unit
return round(new_temp,2), new_unit
else:
return round(self.val,2), self.unit
def kelvin(self):
if self.unit == "F":
new_temp = (self.val - 32)*(5/9) + 273.15
self.unit = "K"
new_unit = self.unit
return round(new_temp,2), new_unit
elif self.unit == "C":
new_temp = self.val + 273.15
self.unit = "K"
new_unit = self.unit
return round(new_temp,2), new_unit
else:
return round(self.val,2), self.unit
def __str__(self):
self.val,self.unit = self.kelvin()
return str(self.val) + ' ' + str(self.unit)
t1 = Temperature(31, "F")
print(t1)
希望这有帮助。您只需要实现_ustr__;方法。 它就像Java的toString() 这将实现以下目的:
def __str__(self):
return "%f %s"%(self.val,self.unit)