Trying to call the gcd from the constructor but I keep getting either a global error or gcd is not defined error. Any suggestions? The program is supposed to reduce fractions immediately. So I got rid of the add.

class Fraction:
    def __init__(self,m,n):
        self.num = m
        self.den = n
        gcd()
        

    def __str__(self):
        return str(self.num)+"/"+str(self.den)

    def show(self):
        print self.num,"/",self.den

    #Assume that m and n are greater than zero
    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 __cmp__(self,otherfraction):
        num1 = self.num*otherfraction.den
        num2 = self.den*otherfraction.num
        if num1 < num2:
    	     return -1
    	else:
            if num1 == num2:
                return 0
            else:
                return 1
class Fraction:
  def __init__(self):
    pass
  def gcd(self, n, m):
    while m % n != 0:
      m, n = n, m %  n
    return n
    
n = Fraction()
print n.gcd(6, 3)

from fractions import gcd

print gcd(6, 3)
commented: nice +7
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.