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"
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器