モジュールを使用せずに、入力値に基づいてさまざまな算術関数を実行する有理数クラスを構築しようとしていfractions
ます。2 つの異なる分数を使用している場合、コードは正常に動作しますが、整数を使用しようとするとすぐに以前のクラス関数でエラーが発生し、その理由がわかりません。この時点で実装しようとしているのは、ここでも整数を有理数に加算することです (例: print Rational(1,2) * 3
)。
これまでのコードを以下に含めました-問題のある操作は です__radd__
が、これがコードに含まれていると、属性エラーが発生します__add__
(このエラーは、この新しい操作が含まれるまで表示されません)。問題は、まだ 2 番目の__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'