0

我正在尝试构建一个有理数类,该类将在不使用fractions模块的情况下根据输入值执行各种算术函数。当我使用两个不同的分数时,代码可以正常工作,但是一旦我尝试使用整数,我就会在早期的类函数中遇到错误并且不确定原因。在这一点上我试图实现的是,再次将一个整数添加到一个有理数(例如,print Rational(1,2) * 3)。

我已经在下面包含了到目前为止的代码 - 有问题的操作是__radd__,尽管当它包含在我的代码中时,我收到一个属性错误__add__(在包含这个新操作之前,这个错误不会出现)。我猜问题出在第二个__radd__参数仍然是其他参数(假设 Rational 类的情况不同?),但我不确定如何继续。

编辑:我正在使用 Python 2.7。示例运行的错误包含在代码下方。

def gcd(a, b):
    if b == 0:
        return a
    else:
        return gcd(b, a%b)
class Rational:
    def __init__(self, nom, denom):
        if denom == 0:
            raise ZeroDivisionError, ("Cannot divide by zero!")
        else:
            self.reduce = gcd(nom, denom)
            self.nom = nom / self.reduce
            self.denom = denom / self.reduce
    def __add__ (self, other):
        return Rational(self.nom*other.denom+other.nom*self.denom, self.denom*other.denom)        
    def __sub__ (self, other):
        return Rational(self.nom * other.denom - other.nom * self.denom,self.denom * other.denom)    
    def __mul__ (self, other):
        return Rational(self.nom * other.nom, self.denom * other.denom)
    def __div__ (self, other):
        return Rational(self.nom * other.denom, self.denom * other.nom)
    def __radd__ (self, other):
        return Rational(self.nom*1+other*self.denom, self.denom*1) 
    def __str__ (self):
        return str(self.nom) + "/" + str(self.denom)

样本错误

print Rational(1,2) + 1

AttributeError                            Traceback (most recent call last)
<ipython-input-201-1ccb1fc0dfef> in <module>()
----> 1 print Rational(1,2) + 1

C:\Users\turk\Documents\EV_HW6_P2.py in __add__(self, other)
     13             self.denom = denom / self.reduce
     14     def __add__ (self, other):
---> 15         return Rational(self.nom*other.denom+other.nom*self.denom, self.denom*other.denom)
     16     def __sub__ (self, other):
     17         return Rational(self.nom * other.denom - other.nom * self.denom,self.denom * other.denom)

AttributeError: 'int' object has no attribute 'denom' 
4

1 回答 1

1

当 PythonRational在左侧看到时,+它使用__and__,但如果Rational左侧没有尺寸但在右侧,则 Python 使用__radd__. (r名义上的__radd__意思right

__add__你使用other.nomother.denom不存在的int所以Rational(1,2) + 1不起作用。

1 + Rational(1,2)有效,因为在__radd__你使用other而不是other.nomother. denom

您可以isinstance(other, int)用来识别int和进行不同的计算__add__,它适用于Rational+intRational+Rational

def __add__ (self, other):
    if isinstance(other, int):
        # Rational + int
        return Rational(self.nom*1+other*self.denom, self.denom*1) 
    else:
        # Rational + Rational
        return Rational(self.nom*other.denom+other.nom*self.denom, self.denom*other.denom)        

# ----

print(Rational(1,2) + 1)
print(Rational(1,2) + Rational(1,2))
于 2016-10-31T03:10:21.440 回答