1. 问题描述
通过构造Fraction类实现两个分数相加。
由于类中show()方法的普适性不够强以及要满足数据类型相加的原因,因此我们对__str__()方法与__add__()方法进行重写。
2. 代码实现
- Fraction.py
# Class
class Fraction():
def __init__(self, top, bottom): # 构造函数
self.num = top
self.den = bottom
def gcd(self, m, n): # 求解最大公约数
while m % n != 0:
oldm = m
oldn = n
m = oldn
n = oldm % oldn
return n
def __add__(self, other_fraction):
new_num = self.num * other_fraction.den + \
self.den * other_fraction.num
new_den = self.den * other_fraction.den
# In order to get the simplified version
gcd = self.gcd(new_num, new_den)
return Fraction(new_num // gcd, new_den // gcd)
def __eq__(self, other):
# cross multiply
first_num = self.num * other.den
second_num = self.den * other.num
return first_num == second_num
def __str__(self):
return f'{self.num}/{self.den}'
- test.py
from Fraction import *
def run_task():
f1 = Fraction(1,4)
f2 = Fraction(1,2)
f3 = f1+f2
print(f'{f1} + {f2} = {f3}')
print('----Equal or not?----')
f4 = Fraction(2,4)
print(f'f1 == f4? {f1 == f4}')
print(f'f2 == f4? {f2 == f4}')
if __name__ == '__main__':
run_task()
- Running_result_on_console
1/4 + 1/2 = 3/4
3. 注意点
- 类中一个方法调用另一个方法时,需要在前面加上self。
- 函数方法重载可以提高程序运行的灵活性。