定义有理数类Python
时间: 2024-09-14 10:08:47 浏览: 67
在Python中,我们可以自定义一个有理数类(Rational Number Class),通过继承内置的`numbers`模块中的` Rational`类或直接创建一个类来实现。下面是一个简单的例子,展示如何定义一个名为`CustomRational`的有理数类:
```python
from fractions import Fraction
class CustomRational:
def __init__(self, numerator, denominator):
# 检查分母是否为0,避免除以零错误
if denominator == 0:
raise ValueError("Denominator cannot be zero.")
self.numerator = numerator
self.denominator = abs(denominator) # 取绝对值以确保正数表示
def __add__(self, other):
return CustomRational(self.numerator * other.denominator + other.numerator * self.denominator,
self.denominator * other.denominator)
def __sub__(self, other):
return CustomRational(self.numerator * other.denominator - other.numerator * self.denominator,
self.denominator * other.denominator)
def __mul__(self, other):
return CustomRational(self.numerator * other.numerator, self.denominator * other.denominator)
def __truediv__(self, other):
if isinstance(other, CustomRational):
return CustomRational(self.numerator * other.denominator, self.denominator * other.numerator)
else:
return CustomRational(self.numerator * other, self.denominator)
def __str__(self):
return f"{self.numerator}/{self.denominator}"
# 示例用法
r1 = CustomRational(4, 7)
r2 = CustomRational(3, 5)
print(r1 + r2) # 输出:(29/35)
```
在这个`CustomRational`类中,我们实现了加法 (`__add__`)、减法 (`__sub__`)、乘法 (`__mul__`) 和除法 (`__truediv__`) 这些基本操作,以及字符串转换 (`__str__`) 方法。用户可以创建这个类的实例,并像处理标准的有理数一样使用它们。
阅读全文