目标:定义分数类,使两个分数可以进行加减乘除等操作
代码实现:
class Fraction1: def __init__(self,up,down): self.up = up self.down = down def __str__(self): return str(self.up)+"/"+str(self.down) def add(self,other): up1 = self.up * other.down + self.down * other.up down1 = self.down * other.down return Fractionl(up1,down1) # add def sub(self,other): up1 = self.up * other.down - self.down * other.up down1 = self.down * other.down return Fraction1(up1,down1) # subtract def multi(self,other): up1 = self.up * other.up down1 = self.down * other.down return Fraction1(up1,down1) # multi def div(self,other): up1 = self.up * other.down down1 = self.down * other.up return Fraction1(up1,down1) # div
创建对象并调用类中”加法“构造函数
f1 = Fraction1(1,2) f2 = Fraction1(1,3) print(f1,f2,f1.add(f2)) #输出结果结构为数1、数2、数1+数2
结果展示:
创建对象并调用类中”减法“构造函数
f1 = Fraction1(1,2) f2 = Fraction1(1,3) print(f1,f2,f1.sub(f2)) #输出结果结构为数1、数2、数1-数2
结果展示:
创建对象并调用类中”乘法“构造函数
f1 = Fraction1(1,2) f2 = Fraction1(1,3) print(f1,f2,f1.multi(f2))
结果展示:
创建对象并调用类中”除法“构造函数
f1 = Fraction1(1,2) f2 = Fraction1(1,3) print(f1,f2,f1.div(f2))
结果展示:
标签:分数,f1,f2,Python,self,Fraction1,down,other,加减乘除 From: https://www.cnblogs.com/wyy-25/p/18215957