python实现有理数类
时间: 2024-04-28 18:16:19 浏览: 22
Python可以通过定义一个有理数类来实现有理数的操作。下面是一个简单的Python有理数类的示例:
```python
class Rational:
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
def __str__(self):
return f"{self.numerator}/{self.denominator}"
def __add__(self, other):
if isinstance(other, Rational):
new_numerator = self.numerator * other.denominator + other.numerator * self.denominator
new_denominator = self.denominator * other.denominator
return Rational(new_numerator, new_denominator)
else:
raise TypeError("Unsupported operand type: +")
def __sub__(self, other):
if isinstance(other, Rational):
new_numerator = self.numerator * other.denominator - other.numerator * self.denominator
new_denominator = self.denominator * other.denominator
return Rational(new_numerator, new_denominator)
else:
raise TypeError("Unsupported operand type: -")
def __mul__(self, other):
if isinstance(other, Rational):
new_numerator = self.numerator * other.numerator
new_denominator = self.denominator * other.denominator
return Rational(new_numerator, new_denominator)
else:
raise TypeError("Unsupported operand type: *")
def __truediv__(self, other):
if isinstance(other, Rational):
new_numerator = self.numerator * other.denominator
new_denominator = self.denominator * other.numerator
return Rational(new_numerator, new_denominator)
else:
raise TypeError("Unsupported operand type: /")
```
上述代码定义了一个有理数类`Rational`,它包含了有理数的分子和分母属性,并重载了加法、减法、乘法和除法运算符。通过创建`Rational`类的实例,可以进行有理数的运算。