Python:自定义算术运算符

本文详细探讨了Python中如何自定义算术运算符,包括使用`__add__`, `__sub__`, `__mul__`, `__truediv__`等特殊方法实现加减乘除。通过实例解析,展示了自定义运算符在类设计中的应用,帮助读者掌握Python的魔法方法及其在定制类型行为中的关键作用。" 115095770,10535885,PHP通过header发送与接收自定义数据教程,"['PHP', '网络编程', 'HTTP协议', '数据传输', 'cURL']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#!/usr/bin/env python
# coding:UTF-8


"""
@version: python3.x
@author:曹新健
@contact: 617349013@qq.com
@software: PyCharm
@file: 自定义算术运算符.py
@time: 2018/10/18 10:48
"""

'''
对象的+、-、*、/、%、//操作分别是由__add__、__sub__、__mul__、__truediv__、
__mod__、__floordiv__,以下程序片段自定义了有理数的+、-、*、/,即类似1/2  + 1/3的操作
'''

class RationalNumber():
    def __init__(self,numerator,denominator):
        self.numerator = numerator
        self.denominator = denominator

    #定义加法+
    def __add__(self, other):
        return RationalNumber(self.numerator * other.denominator + self.denominator *
                              other.numerator,self.denominator * other.denominator)

    #定义减法-
    def __sub__(self, other):
        return RationalNumber(self.numerator * other.denominator - self.denominator *
                              other.numerator,self.denominator * other.denominator)

    #定义乘法*
    def __mul__(self, other):
        return RationalNumber(self.numerator * 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值