#!/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 *
Python:自定义算术运算符
最新推荐文章于 2025-06-06 21:47:10 发布