我正在尝试以前缀作为对象减去。
这是我的代码
class Prefix:
def __init__(self, m=0, cm=0):
self.m = m
self.cm = cm
def __sub__(self, other):
centim = self.cm - other.cm
meter = (self.m - other.m) - abs(centim/100)
if meter < 1:
centim = m*100
meter = 0
return Prefix(meter, cm)
我正在尝试以产生负厘米值的方式减去并从仪表对象获取1m的距离,以实现这一目标
Prefix(2, 20) - Prefix(1, 30) == Prefix(0, 90)
答案 0 :(得分:2)
首先,请记住,对于给定的长度,数百个位置右侧的所有内容都将进入cm
,其左侧或左侧的所有内容都除以100,然后进入{{1 }}。
鉴于此,我们可以重现此问题,将两个m
对象都转换为它们的全长,在那里进行计算,然后从结果中创建一个新的Prefix
:
Prefix
输出:
class Prefix:
def __init__(self, m=0, cm=0):
self.m = m
self.cm = cm
def __sub__(self, other):
self_length = self.m * 100 + self.cm
other_length = other.m * 100 + other.cm
result_length = self_length - other_length
result_m, result_cm = divmod(result_length, 100)
return Prefix(result_m, result_cm)
result = Prefix(2, 20) - Prefix(1, 30)
print(result.m, result.cm)
既然我们走了这么远,我们不妨存储一个“长度”并重载0 90
来使结果更漂亮:
__repr__
输出:
class Prefix:
def __init__(self, length):
self.length = length
def __sub__(self, other):
result_length = self.length - other.length
return Prefix(result_length)
def __repr__(self):
result_m, result_cm = self.split_up(self.length)
if result_m > 0:
return f'{result_m}m {result_cm}cm'
else:
return f'{result_cm}cm'
@staticmethod
def split_up(length):
return divmod(length, 100)
Prefix(220) - Prefix(130)