def gcd(bigger, smaller):
"""Calculate the greatest common divisor of two positive integers."""
print('in gcd')
if not bigger > smaller: # swap if necessary so bigger > smaller
bigger, smaller = smaller, bigger
while smaller != 0: # 1. if smaller == 0, halt
remainder = bigger % smaller # 2. find remainder
# print('calculation, big:{}, small:{}, rem:{}'.\
# format(bigger, smaller, remainder)) # debugging
bigger, smaller = smaller, remainder # 3. reapply
return bigger
def lcm (a,b):
"""Calculate the lowest common multiple of two positive integers."""
print('in lcm')
return (a*b)//gcd(a,b) # Equation 12.1, // ensures int is returned
class Rational(object):
""" Rational with numerator and denominator. Denominator
parameter defaults to 1"""
def __init__(self,numer,denom=1):
print('in constructor')
self.numer = numer
self.denom = denom
def __str__(self):
""" String representation for printing"""
print('in str')
return str(self.numer)+'/'+str(self.denom)
def __repr__(self):
""" Used in interpreter. Call __str__ for now """
print('in repr')
return self.__str__()
def __div__(self, param_Rational):
print("in div")
new_param = Rational(param_Rational.denom, param_Rational.numer)
return self.__mul__(new_param)
def __mul__(self, param_Rational):
print("in mult")
if type(param_Rational) == int:
param_Rational = Rational(param_Rational)
if type(param_Rational) == Rational:
new_numerator = self.numer * param_Rational.numer
new_denominator = self.denom * param_Rational.denom
return Rational(new_numerator, new_denominator)
else:
raise("type error")
def __rmul__(self, param):
print("in rmul")
return self.__mul__(param)
当我尝试实施>>> Rational(4, 1) / Rational(2, 1)
时
但它显示type error "unsupported operand type(s) for /: 'Rational' and 'Rational'"
,表明未实现除法功能。
我认为除法函数应该像上面的代码“ div ”一样实现,所以我现在不知道这个代码有什么问题。请问有人可以提出一些建议吗?
答案 0 :(得分:0)
Python 3.x中未使用__div__()
方法。而是实施__truediv__()
。