我有一个Fraction类的代码
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 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)
def __eq__(self, other):
firstnum = self.num * other.den
secondnum = other.num * self.den
return firstnum == secondnum
当我运行它并尝试添加两个分数时,会弹出说
File "/Users/----/Downloads/Listings/listing_1_9.py", line 25,
in __add__
common = gcd(newnum,newden)
NameError: global name 'gcd' is not defined
答案 0 :(得分:1)
在您的代码中,gcd
是一种分数方法,因此在从另一种方法中引用它时应使用self.gcd
。
答案 1 :(得分:1)
改为使用self.gcd
。
NameError: global name 'gcd' is not defined
那是因为gcd不是全球性的。它是Fraction
的方法。