Python 自定义运算符

Python 自定义运算符

正向运算符
+  __add__(self, other)
-  __sub__(self, other)
*  __mul__(self, other)
/  __truediv__(self, other)
// __floordiv__(self, other)
%  __mod__(self, other)
** __pow__(self, other)
<  __lt__(self, other)
>  __gt__(self, other)
== __eq__(self, other)
示例
import math


class Fraction:
    def __init__(self, numerator: int, denominator: int):
        if denominator == 0:
            raise Exception("denominator can't be 0")
        self.numerator = numerator
        self.denominator = denominator

    def __str__(self):
        return f"{self.numerator}/{self.denominator}"

    def __add__(self, other):
        # 最小公分母
        d = Fraction.lcm(self.denominator, other.denominator)
        return Fraction(d // self.denominator * self.numerator + d // other.denominator * other.numerator, d).simplify()

    def __sub__(self, other):
        # 最小公分母
        d = Fraction.lcm(self.denominator, other.denominator)
        return Fraction(d // self.denominator * self.numerator - d // other.denominator * other.numerator, d).simplify()

    def __mul__(self, other):
        return Fraction(self.numerator * other.numerator, self.denominator * other.denominator).simplify()

    def __floordiv__(self, other):
        return Fraction(self.numerator * other.denominator, self.denominator * other.numerator).simplify()

    # 分数化简
    def simplify(self):
        g = math.gcd(self.numerator, self.denominator)
        return Fraction(self.numerator // g, self.denominator // g)

    # 最小公倍数
    @staticmethod
    def lcm(n1, n2: int) -> int:
        g = math.gcd(n1, n2)
        return g * (n1 // g) * (n2 // g)


def test_fraction():
    assert f"{Fraction(1, 5)}" == "1/5"
    assert f"{Fraction(6, 10).simplify()}" == "3/5"
    assert f"{Fraction(1, 5) + Fraction(2, 5)}" == "3/5"
    assert f"{Fraction(1, 3) + Fraction(1, 2)}" == "5/6"
    assert f"{Fraction(1, 2) - Fraction(1, 3)}" == "1/6"
    assert f"{Fraction(1, 3) - Fraction(1, 2)}" == "-1/6"
    assert f"{Fraction(1, 3) * Fraction(1, 2)}" == "1/6"
    assert f"{Fraction(1, 3) // Fraction(1, 2)}" == "2/3"
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值