1

我有这个类,它需要一个整数和一个分数,然后将它们加在一起。然而,问题是__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))

任何解决此问题的帮助将不胜感激。

4

1 回答 1

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)
于 2013-05-24T00:36:22.697 回答