import math
class rational:
def __init__(self,p,q):
self.p = p
self.q = q
def __str__(self):
return "{} / {}".format(self.p,self.q)
def simplify(self):
gcd = math.gcd(self.p,self.q)
return rational(int(self.p / gcd),int(self.q / gcd))
#加
def __add__(self, other):
return rational(self.p + other.p,self.q + other.q)
#减
def __sub__(self, other):
return rational(self.p * other.q - other.p * self.q,self.q * other.q)
#乘
def __mul__(self, other):
return rational(self.p * other.p,self.q * other.q)
#除
def __div__(self, other):
return rational(self.p * other.q,self.q * other.p)
#相等
def __eq__(self, other):
fz = self.simplify()
fm = other.simplify()
return fz.p == fm.p and fz.q == fm.q
def __float__(self):
return float(self.p / self.q)
Python中一切皆对象,如常见的加(+)、减(-)、乘(*)、除(/)、相等(==)都是调用类中的某个方法
eg:
self:指的是调用该函数的对象,指代的是对象本身,和Java中的this相同
r = rational(1,2)
r1 = rational(1,4)
r + r1表示r对象调用+方法,也就是__add__方法,传入r1对象作为参数,可以理解为
r.+(r1)
同理减、乘、除都是
__xx __()的函数叫做魔法方法,指的是具有特殊功能的函数
1、__init __()
2、__str __()
3、__repr __()
eg:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f'Point({self.x}, {self.y})'
def __repr__(self):
return f'Point(x={self.x}, y={self.y})'
point = Point(2, 3)
print(str(point)) # 输出: Point(2, 3)
print(repr(point)) # 输出: Point(x=2, y=3)
4、__del __()
当删除对象时,python解释器也会默认调用__del __()方法
del 对象