我正在尝试构建一个有理数类,该类将在不使用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'