首页 > 编程语言 >Python 自定义运算符

Python 自定义运算符

时间:2023-08-16 17:45:39浏览次数:55  
标签:__ 自定义 Python self denominator numerator 运算符 other Fraction

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"

标签:__,自定义,Python,self,denominator,numerator,运算符,other,Fraction
From: https://www.cnblogs.com/goallin/p/17635780.html

相关文章

  • Python学习日记 2023年8月16日
    fromseleniumimportwebdriver##pipinstallseleniumfromtimeimportsleepimportcsvf=open('口红1.csv',mode='a',encoding='utf-8',newline='')#csv.DictWriter字典写入csv_writer=csv.DictWriter(f,fieldnames=[......
  • v-charts 自定义堆叠面积图背景颜色
    下载npmiv-charts-Smain.js引入importVeLinefrom'v-charts/lib/line.common'Vue.component(VeLine.name,VeLine)使用<ve-line:data="chartData":settings="chartSettings"></ve-line>exportdefault{data(){......
  • pythonOCC 将二维坐标转化为三维坐标
    OCC当中提供了多种方式转换直接转换为三维坐标使用V3d_View.ProjReferenceAxe()会返回有6个元素的元组,前三位分别对应XYZ例子self._display.View.ProjReferenceAxe()但是,这种方式转换的坐标让人有点摸不着头脑,不推荐 通过求交点获取这种方式会把鼠标限制与某一个面上,......
  • 拿到开发板需要做的事情 -- 配置Python环境
    1.查看系统时间date-R 2.修改系统时间windows上时间项目时间正常,Ubuntu16.04上时间错误-贾斯丁哔哔-博客园(cnblogs.com) 3.安装pip3sudoapt-getupdatesudoapt-getinstallpython3-pip ......
  • python类型标注self
    起因假设有如下代码,我想标注类方法的返回值为自己本身classQueue:def__init__(self):self.items=[]defenqueue(self,item)->Queue:self.items.append(item)returnself用Queue来标注返回值类型,但是呢,运行时Python会报错Traceb......
  • python中自定义类对象json字符串化的方法
    1.用json或者simplejson就可以2.定义转换函数:defconvert_to_builtin_type(obj):print'default(',repr(obj),')'#把MyObj对象转换成dict类型的对象d={}d.update(obj.__dict__)returnd 3.定义类classObject():name=""size=0def__init__(......
  • python不同包之间调用提示不存在
     python不同包之间调用提示不存在 在file-setting-project-projectSources,把包放入到Sources中 再次查看,正常 ......
  • 常用文件读取(python)
    CSV文件CSV(Comma-SeparatedValues)是一种常见的文本文件格式,用于存储结构化的数据。CSV文件中的数据是以逗号(或其他指定的分隔符)分隔的文本行,每一行表示一条记录,每个字段表示记录中的一个属性或值。读CSVimportcsvimportcodecsfile_name=""withopen(file_name,"r",en......
  • 计数排序(Python)
    defcounting(data):"data里的value作为计数数组counts的index,然后把counts的value转换成data的index"#计数列表,存储每个值有多少个,以data的值作为索引,所以数组长度以最大值+1为准counts=[0foriinrange(max(data)+1)]#同时给数组赋初值0,等会逐个计数......
  • if语句条件判断大集合--------------------------------------python语言学习
    准备数据: ##实现成绩大于等于600为优秀,其他为普通等级上代码:importpandasaspddf=pd.read_excel('C:/Users/Administrator/Desktop/test1.xlsx',header=1)defscore_if(score):ifscore>=600:a="优秀"returnaelse:a="普通"......