Python:自定义算术运算符

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


"""
@version: python3.x
@author:曹新健
@contact: [email protected]
@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 * other.numerator,self.denominator *
                              other.denominator)

    #定义除法/
    def __truediv__(self, other):
        return RationalNumber(self.numerator * other.denominator,self.denominator *
                              other.numerator)

    def __str__(self):
        return "{numerator}/{denominator}".format(**vars(self))


if __name__ == "__main__":
    r1 = RationalNumber(1,2)
    r2 = RationalNumber(1,3)
    print(r1 + r2)
    print(r1 - r2)
    print(r1 * r2)
    print(r1 / r2)

 

你可能感兴趣的:(Python基础知识,Python基础知识)