Sanjay Thapa
Sanjay Thapa

Reputation: 98

Issue while using class and function to find a result using recursion in Python

I am trying to find the result recursively by defining a recursive function. The recursive function is defined inside the class.

class Factorial:
    def __init__(self):
        pass

    def getFactorial(self, n):
        # exclude negative numbers
        if n < 0:
            return -1
        # base or terminal case (0! = 1, 1! = 1)
        elif n < 2:
            return 1
        else:
            return n * getFactorial(n - 1)

test = Factorial()
print(test.getFactorial(5))

While running this code, I get this error:

Traceback (most recent call last):
  File "Factorial.py", line 35, in <module>
    print(test.getFactorial(5))
  File "Factorial.py", line 32, in getFactorial
    return n * getFactorial(n - 1)
NameError: name 'getFactorial' is not defined"

But when I use the following code without defining a class, it works perfectly with the correct answer:

def getFactorial(n):
    # base or terminal case (0! = 1, 1! = 1)
    if n < 0:
        return -1
    elif n < 2:
        return 1
    else:
        return n * getFactorial(n - 1)

def main():
    output = getFactorial(5)
    print(output)

if __name__ == "__main__":
    main()

How can I resolve the issue if I were to use the class to solve the same problem?

Upvotes: 1

Views: 121

Answers (1)

Mureinik
Mureinik

Reputation: 311853

Since it's an instance method, you should call it on an instance - in this case, the current instance, self:

return n * self.getFactorial(n - 1)
# Here ----^

Upvotes: 1

Related Questions