我有这个类,它需要一个整数和一个分数,然后将它们加在一起。然而,问题是__add__
这里的函数将答案转换为 a__str__
所以当我尝试打印__repr__
附加问题的答案时,它只打印str
答案的 a 。
from fractions import Fraction
class MixedNumber(object):
def __init__(self, whole_number, fraction):
self.whole_number = whole_number
self.fraction = fraction
def __repr__(self):
return "MixedNumber({}, Fraction({}, {})".format(self.whole_number, self.fraction.numerator, self.fraction.denominator)
def __add__(self, g):
summed = 0
for v in (self.whole_number, g.whole_number, self.fraction, g.fraction):
summed = Fraction(summed.numerator * v.denominator +
v.numerator * summed.denominator,
summed.denominator * v.denominator)
whole = summed.numerator // summed.denominator
remainder = Fraction(summed.numerator * whole.denominator -
whole.numerator * summed.denominator,
summed.denominator * whole.denominator)
return '{} and {}'.format(whole,remainder)
if __name__=='__main__':
x = MixedNumber(3, Fraction(1, 3))
y = MixedNumber(-1, Fraction(2, 5))
z = x + y
print(z)
print(z.__repr__())
例如:这个的输出是
2 and 11/15
'2 and 11/15'
什么时候应该
2 and 11/15
MixedNumber(2, Fraction(11, 15))
任何解决此问题的帮助将不胜感激。