def gcd(m,n):
while m%n != 0:
oldm = m
oldn = n
m = oldn
n = oldm%oldn
return n
class Fraction:
def __init__(self,top,bottom):
self.num = top
self.den = bottom
def __str__(self):
return str(self.num)+"/"+str(self.den)
def show(self):
print(self.num,"/",self.den)
def __add__(self,otherfraction):
newnum = self.num*otherfraction.den + \
self.den*otherfraction.num
newden = self.den * otherfraction.den
common = gcd(newnum,newden)
return Fraction(newnum//common,newden//common)
def __eq__(self, other):
firstnum = self.num * other.den
secondnum = other.num * self.den
return firstnum == secondnum
x = Fraction(1,2)
y = Fraction(2,3)
print(x+y)
print(x == y)
python定义类实例
最新推荐文章于 2024-05-03 15:54:04 发布
本文展示了如何使用Python定义一个分数类`Fraction`,包括初始化方法、字符串表示、显示方法以及实现分数的加法操作。通过`__add__`方法实现了两个分数的相加,并通过`__eq__`方法比较两个分数是否相等。示例中创建了分数`Fraction(1, 2)`和`Fraction(2, 3)`,并进行了加法运算和相等性判断。
摘要由CSDN通过智能技术生成