【发布时间】:2014-03-07 20:18:59
【问题描述】:
(首先是的,我确实知道分数模块存在,但我正在自己练习!) 我的问题是,有这个代码:
class Fraction(object):
def __init__(self,num,den=1,reduce=True):
# only accept integers
if not(type(num) == int and type(den) == int):
raise RuntimeError("You must pass integers as numerator \
and denominator!")
# don't accept fractions with denominator 0
if den == 0:
raise ZeroDivisionError("The denominator must not be 0")
# if both num and den are negative, flip both
if num < 0 and den < 0:
num = abs(num)
den = abs(num)
# if only the den is negative, change the "-" to the numerator
elif den < 0:
num *= -1
den = abs(den)
self.num = num
self.den = den
# the self.auto is a variable that will tell us if we are supposed to
#automatically reduce the Fraction to its lower terms. when doing some
#maths, if either one of the fractions has self.auto==False, the result
#will also have self.auto==False
self.auto = reduce
if self.auto:
self.reduce()
def reduce(self):
'''used to reduce the fraction to its lower terms using Euclid's\
Algorith'''
a = self.num
b = self.den
# With the Euclid's Algorithm, the GCD of A and B, is B if B divides
#evenly A. Otherwise, make B the new A, and make B the remainder of A/B!
#e.g.(30,20). 30/20 is not integer... (30-20=10)
# 20/10 = integer! 10 is the GCD of 20 and 30
while a%b != 0:
olda = a
oldb = b
a = oldb
b = olda%oldb
self.num //= b
self.den //= b
def __add__(self,other):
'''addition implementation'''
if type(other) == int:
other = Fraction(other,1)
elif type(other) == float:
return NotImplemented
num = self.num*other.den + self.den*other.num
den = self.den * other.den
return Fraction(num,den,self.auto and other.auto)
def __radd__(self,other):
'''raddition implemented enables integer + fraction statements'''
# other is always a Fraction!! Well, we are in R(ight)__add__, so this
#was called because the thingy on the right IS a Fraction
# In this case we have to manipulate the "self" argument
if type(self) == int:
self = Fraction(self,1)
elif type(self) == float:
return NotImplemented
num = self.num*other.den + self.den*other.num
den = self.den * other.den
return Fraction(num,den,self.auto and other.auto)
您认为在实现__radd__ 方法时,只需调用__add__ 反转参数是一种好习惯吗?
还是这样做更好? (我假设__add__ 和__radd__ 的答案适用于所有其他数学函数......)
我已经有很多代码了,但为了简洁起见,我认为只有这些就足够了......
(另外,谁能告诉我stackoverflow是否有像剧透标签之类的东西?你知道,在里面写东西但不显示)
【问题讨论】: