类中的 Python 递归
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17843785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python Recursion within Class
提问by Rabbitybunny
I just learn python today, and so am thinking about writing a code about recursion, naively. So how can we achieve the following in python?
我今天刚学python,所以很天真地想写一个关于递归的代码。那么我们如何在python中实现以下功能呢?
class mine:
def inclass(self):
self = mine();
def recur(num):
print(num, end="")
if num > 1:
print(" * ",end="")
return num * self.recur(num-1)
print(" =")
return 1
def main():
a = mine()
print(mine.recur(10))
main()
I tried to define self, but could not think of a way to do so. Any suggestions? Thank you very much.
我试图定义自我,但想不出办法来做到这一点。有什么建议?非常感谢。
Yes the following work, thanks.
是的,以下工作,谢谢。
class mine:
def recur(self, num):
print(num, end="")
if num > 1:
print(" * ",end="")
return num * self.recur(self, num-1)
print(" =")
return 1
def main():
a = mine()
print(mine.recur(mine, 10))
main()
采纳答案by freakish
Each method of a class has to have self
as a first parameter, i.e. do this:
类的每个方法都必须self
作为第一个参数,即这样做:
def recur(self, num):
and it should work now.
它现在应该可以工作了。
Basically what happens behind the scene is when you do
基本上幕后发生的事情是当你这样做时
instance.method(arg1, arg2, arg3, ...)
Python does
Python 确实如此
method(instance, arg1, arg2, arg3, ....)