0

我正在尝试在 Python 中学习 OOP,并制作以下​​代码来覆盖该__plus__方法

class Fraction(object):
    '''Define a fraction type'''
    def __init__(self, num=0, denom=1):
        '''Create a new Fraction with numerator num and denominator demon'''
        self.numerator = num
        if denom != 0:
            self.denominator = denom
        else:
            raise ZeroDivisionError


    def __plus__(self, f):
        num = self.numerator + f.numerator      
        denom = self.numerator + f.denominator
        return "{0}/{1}".format(num, denom)

f = Fraction(1, 6)

print f + f # 我希望结果是 2/12

  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'Fraction'

但它给了我一个错误,我不知道如何解决这个错误,知道吗?

4

2 回答 2

1

您需要覆盖该__add__方法而不是__plus__. 只需尝试替换__plus____add__.

于 2012-10-12T02:38:10.583 回答
1

工作代码:

class Fraction(object):
    '''Define a fraction type'''
    def __init__(self, num=0, denom=1):
        '''Create a new Fraction with numerator num and denominator demon'''
        self.numerator = num
        if denom != 0:
            self.denominator = denom
        else:
            raise ZeroDivisionError

    def __add__(self, f):
        num = self.numerator + f.numerator      
        denom = self.denominator + f.denominator
        return "{0}/{1}".format(num, denom)

请注意,我也修复了denom = self.denominator + f.denominator

于 2012-10-12T02:38:56.527 回答