0

I'm getting a "name not defined error" when I run my program, even though I have defined it in the class.

Here is my Python code:

class Fraction(object):
    """docstring for Fraction"""
    def __init__(self, numerator, denominator):
        self.numerator = numerator
        self.denominator = denominator

    def show(self):
        print(self.numerator, "/", self.denominator)

    def __str__(self):
        return str(self.numerator) + "/" + str(self.denominator)

    def __add__(self, other_fraction):
        new_numerator = self.numerator*other_fraction.denominator + self.denominator*other_fraction.numerator
        new_denominator = self.denominator*other_fraction.denominator

        common = gcd(new_numerator, new_denominator)
        return Fraction(new_numerator//common, new_denominator//common)

    def gcd(numerator, denominator):
        if numerator % denominator == 0:
            return denominator
        else:
            return gcd(denominator, numerator % denominator)



fraction1 = Fraction(3, 5)
fraction2 = Fraction(8, 9)

print(fraction1 + fraction2)

So you guys can tell me some wrong in above code when I execute and catch an error as bellow:

Traceback (most recent call last):
  File "fraction.py", line 31, in <module>
    print(fraction1 + fraction2)
  File "fraction.py", line 17, in __add__
    common = Fraction.gcd(new_numerator, new_denominator)
  File "fraction.py", line 24, in gcd
    return gcd(denominator, numerator % denominator)
NameError: name 'gcd' is not defined
Matt Taylor
  • 3,360
  • 1
  • 20
  • 34
Khai Le
  • 33
  • 4
  • Your method needs to have `self` as the first parameter (3 all together) and has to be called as `self.gcd(numerator, denominator)`. – Klaus D. Nov 11 '15 at 04:21

2 Answers2

0

You can make gcd an instance method

def gcd(self, numerator, denominator):

and use self to call it:

common = self.gcd(new_numerator, new_denominator)

Alternatively, make it a static method:

@staticmethod
def gcd(numerator, denominator):

and call it:

common = Fraction.gcd(new_numerator, new_denominator)

You can check the top answer to this question for more on instance and static methods (and class methods too): What is the difference between @staticmethod and @classmethod in Python?

Community
  • 1
  • 1
Szymon
  • 42,577
  • 16
  • 96
  • 114
  • ... or if you want to do a static method (since OP seems to know about `self`, you could do `Fraction.gcd(...)` – inspectorG4dget Nov 11 '15 at 04:22
  • Thank for your answer, Szymon! But I tried this solution and catch other error: `TypeError: gcd() takes 2 positional arguments but 3 were given` – Khai Le Nov 11 '15 at 04:23
0

gcd probably does not belong in the class itself, but this should make your code work:

def gcd(self, numerator, denominator):
    if numerator % denominator == 0:
        return denominator
    else:
        return self.gcd(denominator, numerator % denominator)
veggie1
  • 717
  • 3
  • 12