Python object usage -
how can utilize value of gcd in add together function. current code throwing error
traceback (most recent phone 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' not defined
code:
class fraction: def __init__(self,top,bottom): self.num=top self.den=bottom def __str__(self): homecoming 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 homecoming n def __add__(self,f1): newnum =self.num*f1.den+self.den*f1.num newden= self.den*f1.den common=gcd(newnum,newden) homecoming fraction(newnum,newden) f2= fraction(3,5) print "first fraction" ,f2 f3= fraction(5,3) print "second fraction",f3 f4=f2+f3 print f4
if you're talking python's fractions
library , its gcd
method, encounter error because never imported gcd
, fractions
import fractions
.
one way solve phone call fractions.gcd
instead. line:
common=gcd(newnum,newden)
should be:
common=fractions.gcd(newnum,newden)
another way import gcd
:
from fractions import gcd
if you're talking not python's library, own __gcd__
method (in case, why reinventing wheel instead of using python's library?), think obvious: should calling self.__gcd__
instead.
python
No comments:
Post a Comment