python 使用类的内置方法定义类

def gcd(m,n):
if n==0:
print("n is not equal 0!")
else:
while m%n!=0:
new=m
m=n
n=new%n
return n
class Fraction():
def __init__(self,m,n):
self.m=m
self.n=n
def __str__(self): #使用内置方法打印结果
if self.m==self.n:
return str(1)
else:
return str(self.m)+'/'+str(self.n)
# def show(self):
# print(self.m,'/',self.n)
def __add__(self, other): #类的内置方法可以进行类的相加
num= self.m*other.n+self.n*other.m
den=self.n*other.n
common=gcd(num,den)
return Fraction(num//common,den//common) #打印输出
def __eq__(self, other): #类的判断,输出True或False
first=self.m*other.n
second=self.n*other.m
return first==second
x=Fraction(3,5)
y=Fraction(3,5)
print(x+y)

猜你喜欢

转载自www.cnblogs.com/masterhu/p/9656341.html
今日推荐