如何在我的add函數中使用gcd的值。目前的代碼是拋出誤差Python對象使用
Traceback (most recent call last):
File "E:/python/pythonclass", line 32, in <module>
f4=f2+f3
File "E:/python/pythonclass", line 22, in __add__
common=gcd(newnum,newden)
NameError: global name 'gcd' is not defined
代碼:
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__(self,a,b):
m=self.a
n=self.b
while m%n !=0:
oldm=n
oldn=n
m=oldn
n=oldm%oldn
return n
def __add__(self,f1):
newnum =self.num*f1.den+self.den*f1.num
newden= self.den*f1.den
common=gcd(newnum,newden)
return Fraction(newnum,newden)
f2= Fraction(3,5)
print "First fraction" ,f2
f3= Fraction(5,3)
print "second fraction",f3
f4=f2+f3
print f4
Python中沒有'gcd()'函數。你似乎期望'__gcd__'方法被調用;你在哪裏得到了它的印象? – 2014-10-11 14:42:26
如果該方法確實被調用,它將忽略其參數並使用實例屬性。 – jonrsharpe 2014-10-11 14:45:29