Python类添加分数

时间:2013-05-24 00:28:54

标签: python class fractions

我有这个类,它需要一个整数和一个分数,并将它们加在一起。但问题是__add__函数将答案转换为__str__,所以当我尝试在答案上打印__repr__时,只会打印一个str 1}}答案。

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))

非常感谢任何解决此问题的帮助。

1 个答案:

答案 0 :(得分:6)

返回MixedNumber的新实例:

return MixedNumber(whole, remainder)

或者,为了使其更加符合类别,type(self)

return type(self)(whole, remainder)

现在你的代码打印出来了:

>>> x = MixedNumber(3, Fraction(1, 3))
>>> y = MixedNumber(-1, Fraction(2, 5))
>>> z = x + y
>>> print z
MixedNumber(2, Fraction(11, 15)
>>> print repr(z)
MixedNumber(2, Fraction(11, 15)

但您可以明确打印__add__的旧结果:

>>> print '{} and {}'.format(z.whole_number, z.fraction)
2 and 11/15

您可以使用__str__方法:

def __str__(self):
    return '{} and {}'.format(z.whole_number, z.fraction)

之后您的print语句将是:

>>> print z
2 and 11/15
>>> print repr(z)
MixedNumber(2, Fraction(11, 15)