#!/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.deno
Python:自定义算术运算符
最新推荐文章于 2024-12-24 23:38:04 发布
本文详细探讨了Python中如何自定义算术运算符,包括使用`__add__`, `__sub__`, `__mul__`, `__truediv__`等特殊方法实现加减乘除。通过实例解析,展示了自定义运算符在类设计中的应用,帮助读者掌握Python的魔法方法及其在定制类型行为中的关键作用。"
115095770,10535885,PHP通过header发送与接收自定义数据教程,"['PHP', '网络编程', 'HTTP协议', '数据传输', 'cURL']

最低0.47元/天 解锁文章

1353

被折叠的 条评论
为什么被折叠?



