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"
posted @   软匠  阅读(58)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
点击右上角即可分享
微信分享提示