Python 覆盖并比较两个对象
我有两个独特的温度对象,我需要相互比较,但是,由于对象可以相等,但单位不同,我比较它们时遇到了麻烦 比如说Python 覆盖并比较两个对象,python,python-3.x,object,initialization,Python,Python 3.x,Object,Initialization,我有两个独特的温度对象,我需要相互比较,但是,由于对象可以相等,但单位不同,我比较它们时遇到了麻烦 比如说 t1=温度(32.0,'F') t2=温度(0.0,'C') 这两个对象是相等的,但我似乎无法得到\uuuueq\uuuuu的正确实现来比较它们 这是我试过的 class Temperature(): def __init__(self, temp = 0.0, unit = 'C'): if float(temp) == str(temp):
t1=温度(32.0,'F')
t2=温度(0.0,'C')
这两个对象是相等的,但我似乎无法得到\uuuueq\uuuuu
的正确实现来比较它们
这是我试过的
class Temperature():
def __init__(self, temp = 0.0, unit = 'C'):
if float(temp) == str(temp):
raise ValueError('could not convert string to float: ' + "'" + str(temp) + "'")
else:
self.t = float(temp)
if unit.upper() not in 'CF':
raise UnitError('Unrecognized temperature unit ' + "'" + str(unit) + "'")
else:
self.u = unit.upper()
def __repr__(self):
return "Temperature({},'{}')".format(self.t, self.u)
def __str__(self):
return str(self.t) + '°' + self.u.upper()
def __eq__(self, other):
t1 = Temperature(self.t, self.u)
t2 = Temperature(other.t, other.u)
other.convert()
if t1.t == t2.t and t1.u == t2.u:
return True
return False
def convert(self):
t = Temperature(self.t, self.u)
if t.u.upper() == 'C':
t.t *= 1.8
t.t += 32
t.u = 'F'
return t
else:
t.t -= 32
t.t /= 1.8
t.u = 'C'
return t
请注意,我确实有一种方法可以将温度从一个单位转换为另一个单位。同样,当两个对象处于不同的单位时,我似乎不知道如何比较它们。我没有仔细查看您的convert函数,但假设它正确返回convert temp,那么这应该可以工作。基本思想是检查单位是否匹配。如果不是,则转换另一个,并将其温度设置为新的刻度。如果单位匹配,只需比较温度
def __eq__(self, other):
other_temp = other.t
if other.u != self.u:
other_temp = other.convert().t
if self.t == other_temp: #already ensured units match
return True
return False
要比较温度,无需始终转换
other
。仅当self
和other
具有不同的单位时,才需要转换。一旦将它们转换为相同的单位,就可以比较温度值
您还从convert()
方法返回了新对象。因此,您需要指定返回值。您应该使用差值的绝对值来避免浮点错误
这应该起作用:
def __eq__(self, other):
if self.u != other.u:
other = other.convert()
return math.fabs(self.t - other.t) < 1e-6
def\uuuuu eq\uuuuu(自身、其他):
如果self.u!=其他.u:
other=other.convert()
返回math.fabs(self.t-other.t)<1e-6
将两者更改为一种类型并允许出现浮点错误:
class Temperature():
def __init__(self, temp=0.0, unit='C'):
if float(temp) == str(temp):
raise ValueError('could not convert string to float: ' + "'" + str(temp) + "'")
else:
self.t = float(temp)
if unit.upper() not in 'CF':
raise Exception
else:
self.u = unit.upper()
def __repr__(self):
return "Temperature({},'{}')".format(self.t, self.u)
def __str__(self):
return str(self.t) + '°' + self.u.upper()
def __eq__(self, other):
t1, t1u = self.t, self.u
t2, t2u = other.t, other.u
other.convert()
self.convert()
equal = abs(self.t - other.t) < .0001
self.t, self.u = t1, t1u
other.t, other.u = t2, t2u
return equal
def convert(self):
if self.u.upper() == 'C':
self.t *= 1.8
self.t += 32
self.u = 'F'
您也不希望在以后无法恢复值的情况下更改实际属性,存储、转换、执行比较,然后将属性重置为原始值,这意味着用户可以恢复输入的值
将温度存储在一个普通单元(如开尔文)中要简单得多
def __init__(self, temp, unit):
temp = float(temp)
# Save the original input, perhaps for display purposes
self.orig = temp
self.unit = unit
if unit == "K":
self.t = temp
elif unit == "C":
self.t = tmp + 273.15
elif unit == "F":
self.t = (temp + 459.67) * 5 / 9.0
else:
raise ValueError("Unrecognized unit %s" % (unit,))
然后比较任意两个温度
只需比较它们的t
属性
def __eq__(self, other):
try:
return abs(self.t - other.t) < 1e-6 # Or some other tolerance
else AttributeError:
return False
# or raise NotImplemented
def\uuuuu eq\uuuuu(自身、其他):
尝试:
返回abs(self.t-other.t)<1e-6#或其他公差
其他属性错误:
返回错误
#或提出不执行的建议
当您compare@PadraicCunningham我对Python还是有点陌生,您必须进行一些扩展。请注意浮点舍入错误。您不能假定需要更改的只有另一个,而且在处理物理量时,您可能会受到浮点限制,在程序中,我总是将它们保持在相同的单位中,并且只有在为用户显示它们时才进行转换。我觉得把一个单位和温度物体联系起来是错误的。这就像说整数应该有某种属性,说明它们是以十六进制、二进制还是十进制打印的,在比较它们时需要参考这样的属性。我的2美分。如果转换是浮点,那么你需要考虑舍入误差,而不是绝对误差equality@sabbahillel谢谢你指出这一点。我已经编辑了我的答案。
def __init__(self, temp, unit):
temp = float(temp)
# Save the original input, perhaps for display purposes
self.orig = temp
self.unit = unit
if unit == "K":
self.t = temp
elif unit == "C":
self.t = tmp + 273.15
elif unit == "F":
self.t = (temp + 459.67) * 5 / 9.0
else:
raise ValueError("Unrecognized unit %s" % (unit,))
def __eq__(self, other):
try:
return abs(self.t - other.t) < 1e-6 # Or some other tolerance
else AttributeError:
return False
# or raise NotImplemented