以下代码是在学习老师的代码后自己尝试敲出来的,半背半理解的状态下写出来的,编程过程也遇到一些问题,最后还是解决了。
from math import gcd
class Faction(object):#定义一个分数类
def __init__(self, num, den):#属性的初始化
if den ==0:
raise ValueError('分母不能为0') #分母不能为0,否则报错
self._num= num
self._den= den
self.simplify() #调用simplify函数
self.normalize()#调用normalize函数
#初始化中分母加了下划线,表示一种特殊隐喻,为分母添加一个访问器,以便可以访问
@property
def num(self):
return self._num
@property
def den(self):
return self._den
def add(self, other):#定义加法函数
return Faction(self._num * other.den + self._den* other.num,\
self._den* other.den)
def sub(self, other):
return Faction(self._num * other.den - self._den* other.num,\
self._den* other.den)
def mul(self, other):
return Faction(self._num * other.num, self._den* other.den)
def div(self, other):
return Faction(self._num * other.den, self._den* other.num)
#方法重载,如果不加重载,在main函数中需要调用add函数才能进行加法运算。
#方法重载后就可以不用调用函数进行加法运算
#注意加法运算是self和other进行加法运算而不是自己和自己。自己编写代码过程中出现了此问题导致运行结果一直不对
def __add__(self, other):
return self.add(other)
def __sub__(self, other):
return self.sub(other)
def __mul__(self, other):
return self.mul(other)
def __truediv__(self, other):
return self.div(other)
#进行分子分母化简
#通过调用内置函数gcd直接求分子和分母的最大公约数
#求出最大公约数后,进行整出求出化简后的分子和分母
def simplify(self):
#分子和分母化简需要分子不为0并且分母不为1的情况下进行
if self._num != 0 and self._den != 1:
factor = gcd(abs(self._num), abs(self._den))
#当最大公约数大于1时,和最大公约数进行整除求出化简后的分子和分母
#当最大公约数为1时,就不需要化简,直接返回自身数值
if factor> 1:
self._num//= factor
self._den//= factor
return self
def normalize(self):
if self._den < 0:
#分母为负数时,将负号放置在分子处,分母变整数
self._num= -self._num
self._den= -self._den
return self
#执行print会打印str函数下所有的东西
def __str__(self):
if self._num == 0:
return '0'
elif self._den == 1:
return str(self._num)
else:
return '%d/%d'% (self._num,self._den)
def main():
f1 = Faction(3, -6)
f2 = Faction(3, 4)
print(f1)
print(f2)
#由于以上使用了方法的重载,所以可以直接写f1+f2,否在需要写成print(f1.add(f2))
print(f1 + f2)
print(f1 - f2)
print(f1 * f2)
print(f1 / f2)
if __name__ == '__main__':
main()