设计一个分数类( fraction ),实现带有默认分母(等于1)的构造 函数,实现分数+
时间: 2023-07-14 16:13:22 浏览: 46
下面是一个简单的分数类的实现,包括默认构造函数和分数加法:
```python
class Fraction:
def __init__(self, numerator, denominator=1):
self.numerator = numerator
self.denominator = denominator
def __add__(self, other):
if isinstance(other, int):
other = Fraction(other)
if self.denominator == other.denominator:
return Fraction(self.numerator + other.numerator, self.denominator)
else:
lcm = self.lcm(self.denominator, other.denominator)
num1 = self.numerator * lcm // self.denominator
num2 = other.numerator * lcm // other.denominator
return Fraction(num1 + num2, lcm)
def lcm(self, a, b):
return abs(a*b) // self.gcd(a, b)
def gcd(self, a, b):
if b == 0:
return a
else:
return self.gcd(b, a % b)
```
这个分数类支持默认分母为1,也可以自定义分母。加法操作可以接受整数或其他分数作为操作数,结果也是一个分数对象。如果两个分数的分母不同,则需要先求出它们的最小公倍数,并将两个分数的分子乘以对应的倍数,然后相加即可。