实现一个分数类,包括加减乘除比大小等操作

def gcd(m, n):
    while m % n != 0:
        oldm = m
        oldn = n
        m = oldn
        n = oldm % oldn
    return n


class Fraction:
    def __init__(self, top, bottom):
        self.num = top
        self.den = bottom

    def show(self):
        print(self.num, "/", self.den)

    def __str__(self):
        # 返回字符串形式的分数
        return str(self.num) + "/" + str(self.den)

    def __add__(self, otherfraction):
        # 两个分数相加
        newnum = self.num * otherfraction.den + self.den * otherfraction.num
        newden = self.den * otherfraction.den
        common = gcd(newnum, newden)
        return Fraction(newnum // common, newden // common)

    def __sub__(self, otherfraction):
        # 两个分数相减
        newnum = self.num * otherfraction.den - self.den * otherfraction.num
        newden = self.den * otherfraction.den
        common = gcd(newnum, newden)
        return Fraction(newnum // common, newden // common)

    def __mul__(self, otherfraction):
        # 两个分数相乘
        newnum = self.num * otherfraction.num
        newden = self.den * otherfraction.den
        common = gcd(newnum, newden)
        return Fraction(newnum // common, newden // common)

    def __truediv__(self, otherfraction):
        # 两个分数相除
        newnum = self.num * otherfraction.den
        newden = self.den * otherfraction.num
        common = gcd(newnum, newden)
        return Fraction(newnum // common, newden // common)

    def __eq__(self, other):
        # 判断两个分数是否相等
        firstnum = self.num * other.den
        secondnum = other.num * self.den
        return firstnum == secondnum

    def __lt__(self, other):
        # 判断两个分数的大小
        firstnum = self.num * other.den
        secondnum = other.num * self.den
        return firstnum < secondnum

    def __gt__(self, other):
        # 判断两个分数的大小
        firstnum = self.num * other.den
        secondnum = other.num * self.den
        return firstnum > secondnum
myf=Fraction(3,5)

print(myf)
f1=Fraction(1,4)
f2=Fraction(1,2)
f3=f1+f2
f4=f1-f2
f5=f1/f2
f6=f1*f2

print(f3)
print(f4)
print(f5)
print(f6)
print(f1>f2)
print(f1<f2)
print(f1==f2)
3/5
3/4
-1/4
1/2
1/8
False
True
False

参考:

Object-Oriented Programming in Python: Defining Classes

Mapping Operators to Functions

python中的@方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值