Python是一门面向对象的编程语言,类的定义和构造很重要。
以下为一个自定义分数类:
#Python编程范式是面对对象,下面为用户自定义一个分数类。
#这个类包含了分数的加减乘除运算和逻辑运算,较为完整。
class Fraction:
def __init__(self,top,bottom):
self.num = top
self.den = bottom
def show(self):
print(self.num,'/',self.den,sep='')
def __str__(self): #若无此函数,直接执行print输出对象会报错。
return str(self.num)+'/'+str(self.den)
def __add__(self,other): #双目运算符+,self指向第一个运算对象,otherfaction指向另一个对象。
new_num = self.num * other.den + self.den * other.num
new_den = self.den * other.den
common = gcd(new_num,new_den)
return Fraction(new_num/common,new_den/common)
def __sub__(self,other): #减法
new_num = self.num * other.den - self.den * other.num
new_den = self.den * other.den
common = gcd(new_num,new_den)
return Fraction(new_num/common,new_den/common)
def __mul__(self,other): #乘法
new_num = self.num * other.num
new_den = self.den * other.den
common = gcd(new_num,new_den)
return Fraction(new_num/common,new_den/common)
def __truediv__(self,other): #除法
new_num = self.num * other.den
new_den = self.den * other.num
common = gcd(new_num,new_den)
return Fraction(new_num/common,new_den/common)
def __eq__(self,other): #判断相等的函数重写,类似c++重载相等运算符
new_num1 = self.num * other.den
new_num2 = other.num * self.den
return new_num1 == new_num2
def __le__(self,other): #<=
new_num1 = self.num * other.den
new_num2 = other.num * self.den
return new_num1 <= new_num2
def __ge__(self,other): #>=
new_num1 = self.num * other.den
new_num2 = other.num * self.den
return new_num1 >= new_num2
def __lt__(self,other): #<
new_num1 = self.num * other.den
new_num2 = other.num * self.den
return new_num1 < new_num2
def __gt__(self,other): #>
new_num1 = self.num * other.den
new_num2 = other.num * self.den
return new_num1 > new_num2
def __ne__(self,other): #!=
new_num1 = self.num * other.den
new_num2 = other.num * self.den
return new_num1 != new_num2
def gcd(m,n): #最大公因数算法,使用欧几里得算法。化简分数
while m % n != 0:
oldm = m
oldn = n
n = oldm
m = oldm % oldn
return n
#建立一些数据用于测试函数。
my_f0 = Fraction(1,2)
my_f1 = Fraction(1,2)
my_f2 = Fraction(-1,2)
my_f3 = Fraction(1,3)
my_f4 = Fraction(2,3)
print(my_f1) #测试输出函数
my_f5 = my_f1 + my_f2
print(my_f5)
my_f6 = my_f4 - my_f3
print(my_f6)
my_f7 = my_f1 * my_f4
print(my_f7)
my_f8 = my_f2 / my_f3
print(my_f8)
print(my_f1 > my_f2,'== 1')
print(my_f1 < my_f2,'== 0')
print(my_f1 >= my_f1,'== 1')
print(my_f1 >= my_f4,'== 0')
print(my_f1 <= my_f2,'== 0')
print(my_f3 <= my_f4,'== 1')
print(my_f1 == my_f0,'== 1')
print(my_f1 != my_f3,'== 1')