首页 > 解决方案 > 使用类和函数在 Python 中使用递归查找结果时出现问题

问题描述

我试图通过定义递归函数来递归地找到结果。递归函数在类内部定义。

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))

运行此代码时,我收到此错误:

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"

但是当我使用以下代码而不定义类时,它与正确答案完美配合:

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()

如果我要使用课程来解决同样的问题,我该如何解决这个问题?

标签: pythonrecursion

解决方案


因为它是一个实例方法,你应该在一个实例上调用它——在这种情况下,是当前实例self

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

推荐阅读