1

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?

4
  • 4
    use self.getFactorial(n - 1) Commented Jan 1, 2020 at 19:52
  • Wow, that works !!! I really appreciate it. Do you mind to explain why I need to add self here. Commented Jan 1, 2020 at 19:54
  • look at this Commented Jan 1, 2020 at 20:06
  • 1
    What are you doing writing code without knowing the basics? Pls read about Python objects, and various method scopes. Commented Jan 1, 2020 at 21:51

1 Answer 1

1

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 ----^
Sign up to request clarification or add additional context in comments.

1 Comment

Your answer is confusing. It’s not a class method, it’s an instance method. Class methods are supposed to be invoked with class names, not instances. Using instances on class methods will generate a warning by code checkers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.