我试图创建一个函数,允许不同分母的分数使用+运算符,同时将结果简化为可被分子和分母的最大公约数整除的分数。你知道吗
class Fraction:
def __init__(self, top, bottom):
self.num = top
self.den = bottom
def __str__(self):
return str(self.num) + "/" + str(self.den)
def gcd(m, n):
while m%n != 0:
oldm = m
oldn = n
m = oldn
n = oldm%oldn
return n
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)
f1 = Fraction(1,4)
f2 = Fraction(1,2)
f3 = f1+f2
print(f3)
我希望输出是3/4
,但出现了以下错误。你知道吗
Traceback (most recent call last):
File "C:\Users\matth\Desktop\MandRfraction.py", line 35, in <module>
f3 = f1+f2
File "C:\Users\matth\Desktop\MandRfraction.py", line 28, in __add__
common = gcd(newnum//common, newden//common)
NameError: name 'gcd' is not defined
我不知道为什么gcd没有定义。你知道吗
它是一个特定于类的函数,又称为“method”(在
Fraction
类中定义),因此您需要将其称为Fraction.gcd
,而不仅仅是gcd
。你知道吗因为它是一个静态的函数(没有连接到任何单独的
Fraction
),所以最好将它标记为:现在可以将其称为
self.gcd(...)
(在任何Fraction
方法中),或者称为Fraction.gcd(...)
(在任何地方)。你知道吗相关问题 更多 >
编程相关推荐