私は入門的なpythonクラスの宿題に取り組んでいます。 目的は*/+ - <> < => =クラス呼び出しの演算子を使用する関数を定義することです。この特定のプログラムは3つのパラメータself, inches, numerator, denominator
を取り、(それを簡素化することができる場合)組み込みクラス関数への演算子の割り当て
コールRulerUnit(2, 1, 4)
私は乗算部に取り組んでいますし、トラブル時にを持っています"2 1/4"
を返す64の要因として分母を保存しますinches
は0
です。inches == 0
またはinches is None
ですか?私のような主張を実行する場合は、とすることができるいずれさらに
: assert(str(RulerUnit(2, 3, 4) * RulerUnit(0, 1, 2)) == "1 3/8")
AssertionError
がrasedされ、自分のコード
print((RulerUnit(2, 3, 4) * RulerUnit(0, 1, 2)))
プリント2 3/8
コード:
def __mul__ (self, other):
if self.inches == 0 and other.inches == 0:
newnum = self.num * other.num
finaldenom = self.denom * other.denom
finalnum = newnum % 64
finalinches = newnum // finaldenom
return RulerUnit(finalinches, finalnum, finaldenom)
elif self.inches == 0 and other.inches != 0:
newnum1 = (self.inches * self.denom) + self.num
finaldenom = self.denom * other.denom
finalnum = (newnum1 * other.num) % 64
finalinches = (newnum1 * other.num) // finaldenom
return RulerUnit(finalinches, finalnum, finaldenom)
elif self.inches!= 0 and other.inches == 0:
newnum1 = (self.inches * self.denom) + self.num
finaldenom = self.denom * other.denom
finalnum = (newnum1 * other.num) % 64
finalinches = (newnum1 * other.num) // finaldenom
return RulerUnit(finalinches, finalnum, finaldenom)
elif self.inches != 0 and other.inches != 0:
newnum1 = (self.inches * self.denom) + self.num
newnum2 = (other.inches * other.denom) + other.num
finaldenom = (self.denom * other.denom) % 64
finalnum = (newnum1 * newnum2) % 64
finalinches = (newnum1 * newnum2) // finaldenom
return RulerUnit(finalinches, finalnum, finaldenom)
okを提案していただきありがとうございます。 –