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"
标签:__,自定义,Python,self,denominator,numerator,运算符,other,Fraction
From: https://www.cnblogs.com/goallin/p/17635780.html