本题自定义一个分数类,类名Fraction,包含分子num和分母den,定义如下
时间: 2024-03-20 07:43:29 浏览: 103
设计一个表示分数的类Fraction。这个类用两个int类型的变量分别表示分子和分母。
5星 · 资源好评率100%
好的,以下是Fraction类的定义:
```python
class Fraction:
def __init__(self, num, den):
self.num = num
self.den = den
def __str__(self):
return f"{self.num}/{self.den}"
def __add__(self, other):
num = self.num * other.den + self.den * other.num
den = self.den * other.den
return Fraction(num, den)
def __sub__(self, other):
num = self.num * other.den - self.den * other.num
den = self.den * other.den
return Fraction(num, den)
def __mul__(self, other):
num = self.num * other.num
den = self.den * other.den
return Fraction(num, den)
def __truediv__(self, other):
num = self.num * other.den
den = self.den * other.num
return Fraction(num, den)
def __eq__(self, other):
return self.num * other.den == self.den * other.num
def __lt__(self, other):
return self.num * other.den < self.den * other.num
def __gt__(self, other):
return self.num * other.den > self.den * other.num
def __le__(self, other):
return self.num * other.den <= self.den * other.num
def __ge__(self, other):
return self.num * other.den >= self.den * other.num
```
Fraction类包含分子num和分母den两个属性,以及加、减、乘、除、比较等运算符的重载方法。我们可以使用这个类来进行分数的各种运算。
阅读全文