這個任務相對簡單。
class Rational(object):
__slots__ = ['numerator', 'denominator']
def __init__(self, numerator, denominator=1):
# initialize and verify, divide both parameters by GCD of both
要實現運營商,使用特殊方法名:
def __add__(self, other):
# add rational to something else
def __radd__(self, other):
# same, but with operands reversed
return self + other
然後繼續執行__sub__
,__mul__
等的完整列表是在Python Data Model: 3.37 Emulating numeric types文檔部分可用。比較運營商被命名爲__lt__
,__le__
等,您可以實現以下方式操作:
def __add__(self, other):
x_numer = self.numerator
x_denom = self.denominator
if isinstance(other, Rational):
y_numer = other.numerator
y_denom = other.denominator
elif isinstance(other, int):
y_numerator = other
y_denominator = 1
else:
return NotImplemented
return Rational(x_numer * y_denom + y_numer * x_denom, x_denom * y_denom)
有你可能實現,像__repr__
和__str__
其他運營商。
我希望這足以讓你開始,其他方法將被編寫成就像上面的__add__
一樣。
親愛的Stackoverflow:我有這個想法,我已經決定了一些有用的東西,請爲我建立它。聘請承包商,我們不在這裏爲你做你的工作。 –
*僱用志願者獲得薪酬:D – Houdini
Timothy Budd的「C++數據結構」具有非常棒的Rational類實現。將其移植到Python:http://www.amazon.com/Classic-Data-Structures-Timothy-Budd/dp/0201508893/ref=sr_1_5?ie=UTF8&qid=1375117863&sr=8-5&keywords=Timothy+Budd+C%2B %2B – duffymo