0

モジュールを使用せずに、入力値に基づいてさまざまな算術関数を実行する有理数クラスを構築しようとしてい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' 
4

1 に答える 1

1

PythonRationalが の左側にある場合+は使用します__and__が、Rational左側のサイズがなく右側にある場合は Python を使用します__radd__。(r名前の__radd__意味right)

In __add__you use other.nomand other.denomwhich is not exist in intsoRational(1,2) + 1は機能しません。

1 + Rational(1,2)andの代わりに__radd__使用するため、機能しますotherother.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 に答える