Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively calling a method inside a class in python

class Example(object):
    def doSomething(self, num):
        if(num < 10 ) : 
            //print the number
        else : 
            //call doSomething() again

Here how do I call the doSomething method in the else condition inside the method?

like image 844
praxmon Avatar asked Jan 05 '23 19:01

praxmon


1 Answers

Call it with self.doSomething(num-1), because doSomething would refer to a global function rather than the one in the class. Also put the print before the if so that it prints the number regardless of what it is (so you can see the numbers decreasing) and put a return in it's place:

class Example(object):
    def doSomething(self, num):
        print num
        if(num < 10 ) : 
            return
        else : 
            self.doSomething(num-1)

>>> x = Example()
>>> x.doSomething(15)
15
14
13
12
11
10
9
>>> 
like image 53
A.J. Uppal Avatar answered Jan 12 '23 05:01

A.J. Uppal