2015-10-08 2 views
0

J'ai un code pour une classe Fractionmodule ne reconnaît pas ma fonction

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 

Quand je lance et essayer d'ajouter deux fractions, il apparaît disant

File "/Users/----/Downloads/Listings/listing_1_9.py", line 25, 
in __add__ 
    common = gcd(newnum,newden) 
NameError: global name 'gcd' is not defined 
+0

essayez self.gcd (newnum, newden) – artsylar

Répondre

1

Dans votre code, gcd est une méthode de fraction, vous devez donc utiliser self.gcd lorsque vous faites référence à l'intérieur d'une autre méthode.

0

Utilisez plutôt self.gcd.

Explication

NameError: global name 'gcd' is not defined 

C'est parce que GCD est pas mondiale. C'est une méthode de Fraction.