所以我创建了一个非常简单的温度等级,它可以将给定温度从摄氏温度转换为华氏温度,反之亦然。问题是我希望有一个"转换"如果直接调用则执行的类中的方法,但如果被赋值给变量则不会执行。这是我的代码:
class Temperature:
def __init__(self,temp=None,cf='C'):
if temp == None:
self.temp = float('0.0')
else:
try:
self.temp = float("{0:.2f}".format(temp))
except:
print('Your temperature must be a number!')
if cf not in ['c','C','f','F']:
print('You must identify the temperature as either F for Fahrenheit or C for Celsius!')
else:
self.cf = cf.upper()
def convert(self):
if self.cf == 'F':
self.temp = float("{0:.2f}".format((self.temp - 32) * 5 / 9))
self.cf = 'C'
return(self)
elif self.cf == 'C':
self.temp = float("{0:.2f}".format((9/5)*self.temp + 32))
self.cf = 'F'
return(self)
def __repr__(self):
return('Temperature({},{})'.format(self.temp,self.cf))
结果:
>>>t1 = Temperature()
>>>t1
Temperature(0.0,C)
>>>t2 = Temperature(100,'f')
>>>t2
Temperature(100.0,F)
>>>t3 = t3 = Temperature('12.5','c')
>>>t3
Temperature(12.5,C) #works fine up to here
>>>t1.convert()
Temperature(32.0,C) #converts when called - just what I want
>>>t4 = t1.convert() #Should set t4 equal TO VALUE of 't1.convert()' without rerunning method
>>>t4
Temperature(0.0,C) #THIS IS WHERE I GET LOST. I want t4 to print out 'Temperature(32.0,C)' Ideas?
答案 0 :(得分:2)
一种方法是创建Temperature
的新实例,并为其转换值,而不修改Temperature
当前实例的值:
def convert(self):
if self.cf == 'F':
return Temperature(float("{0:.2f}".format((self.temp - 32) * 5 / 9)), 'C')
elif self.cf == 'C':
return Temperature(float("{0:.2f}".format((9/5)*self.temp + 32)))
结果:
>>>t1 = Temperature()
>>>t1
Temperature(0.0,C)
>>>t1.convert()
Temperature(32.0,C)
>>>t1
Temperature(0.0,C)
>>>t4 = t1.convert()
>>>t4
Temperature(32.0,C)
答案 1 :(得分:0)
考虑到这一点,当您再次致电t1.convert()
时,它会更改self.cf
值,
所以下次运行 if 条件并返回Instance。
t1 = Temperature()
print t1.convert()
print '======='
print t1.convert()
print '======='
t4 = t1.convert()
print t4
输出: -
C
Temperature(32.0,F)
=======
F
Temperature(0.0,C)
=======
C
Temperature(32.0,F)
答案 2 :(得分:0)
也许你可以做这样的事情?
class TemperatureError(Exception):
pass
class Temperature(object):
def __init__(self, temp=None, scale='C'):
self._celcius = None
self._fahrenheit = None
if temp:
if scale in ('c', 'C'):
self.celcius = temp
elif scale in ('f', 'F'):
self.fahrenheit = temp
else:
raise TemperatureError
@property
def celcius(self):
return self._celcius
@celcius.setter
def celcius(self, temp):
self._celcius = float('{0:.2f}'.format(temp))
self._fahrenheit = float('{0:.2f}'.format((temp - 32) * 5 / 9))
@property
def fahrenheit(self):
return self._fahrenheit
@fahrenheit.setter
def fahrenheit(self, temp):
self._celcius = float('{0:.2f}'.format(temp * 9 / 5 + 32))
self._fahrenheit = float('{0:.2f}'.format(temp))
结果如下:
>>> t = Temperature(20, 'F')
>>> t.fahrenheit
20.0
>>> t.celcius
68.0