python - 使用类和函数在 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()
如果我要使用课程来解决同样的问题,我该如何解决这个问题?
解决方案
因为它是一个实例方法,你应该在一个实例上调用它——在这种情况下,是当前实例self
:
return n * self.getFactorial(n - 1)
# Here ----^
推荐阅读
- entity-framework - SQLite 实体框架代码优先:哪个 Nuget 包?
- airflow - 如何从 Apache Airflow 触发 azure Databricks 笔记本
- karate - 有没有办法捕捉空手道呼叫的请求和响应?
- angular - 单击 ngFor 内的链接时没有任何反应
- c++ - 用 boost::geometry 扩展多边形?
- javascript - React Router 更改 URL 但不更新页面,除非它从浏览器刷新
- windows - 对最近 N 小时内修改的文件运行批处理脚本
- javascript - 我想在这个对象数组中过滤年龄超过 30 岁
- r - 创建一个函数来为一个选择分配一个值,例如 1 是 100,2 是 99 等等......然后通过变量找到总和
- vue.js - 安装 vuetify 后出现问题。“类型错误:无法读取属性 'lang'