建立分数类fraction
时间: 2023-10-14 14:04:14 浏览: 119
class fraction
好的,下面是一个简单的分数类 `Fraction` 的实现:
```python
class Fraction:
def __init__(self, numerator, denominator=1):
if denominator == 0:
raise ZeroDivisionError("Denominator cannot be zero.")
self.numerator = numerator
self.denominator = denominator
def __str__(self):
return f"{self.numerator}/{self.denominator}"
def __repr__(self):
return f"Fraction({self.numerator}, {self.denominator})"
def __eq__(self, other):
if isinstance(other, Fraction):
return self.numerator * other.denominator == self.denominator * other.numerator
elif isinstance(other, int):
return self.numerator == other * self.denominator
else:
return NotImplemented
def __lt__(self, other):
if isinstance(other, Fraction):
return self.numerator * other.denominator < self.denominator * other.numerator
elif isinstance(other, int):
return self.numerator < other * self.denominator
else:
return NotImplemented
def __le__(self, other):
if isinstance(other, Fraction):
return self.numerator * other.denominator <= self.denominator * other.numerator
elif isinstance(other, int):
return self.numerator <= other * self.denominator
else:
return NotImplemented
def __add__(self, other):
if isinstance(other, Fraction):
return Fraction(self.numerator * other.denominator + other.numerator * self.denominator, self.denominator * other.denominator)
elif isinstance(other, int):
return Fraction(self.numerator + other * self.denominator, self.denominator)
else:
return NotImplemented
def __sub__(self, other):
if isinstance(other, Fraction):
return Fraction(self.numerator * other.denominator - other.numerator * self.denominator, self.denominator * other.denominator)
elif isinstance(other, int):
return Fraction(self.numerator - other * self.denominator, self.denominator)
else:
return NotImplemented
def __mul__(self, other):
if isinstance(other, Fraction):
return Fraction(self.numerator * other.numerator, self.denominator * other.denominator)
elif isinstance(other, int):
return Fraction(self.numerator * other, self.denominator)
else:
return NotImplemented
def __truediv__(self, other):
if isinstance(other, Fraction):
return Fraction(self.numerator * other.denominator, self.denominator * other.numerator)
elif isinstance(other, int):
return Fraction(self.numerator, self.denominator * other)
else:
return NotImplemented
```
这个类支持分数的加、减、乘、除运算,以及比较运算符 `<`, `<=`, `==`。注意到我们在实现运算符方法时,对于可能出现的类型不匹配情况,我们返回了 `NotImplemented`,这是为了让 Python 解释器知道我们没有实现这种情况下的运算,从而让它去尝试反向调用运算符方法。例如,如果 `a` 是一个分数,`b` 是一个整数,那么 `a + b` 会先尝试调用 `a.__add__(b)`,如果返回了 `NotImplemented`,则会尝试调用 `b.__radd__(a)`。如果 `b` 也没有实现 `__radd__` 方法,那么就会抛出 `TypeError` 异常。
阅读全文