Recursive method in class

ast none at gmail.com
Fri Sep 27 07:54:19 EDT 2019


Hello

Is it feasible to define a recursive method in a class ?
(I don't need it, it's just a trial)

Here are failing codes:


class Test:
     def fib(self, n):
         if n < 2: return n
         return fib(self, n-2) + fib(self, n-1)

t = Test()

t.fib(6)

---------------------
Traceback (most recent call last):
return fib(self, n-2) + fib(self, n-1)
NameError: name 'fib' is not defined
---------------------

An other try:

class Test:
     @staticmethod
     def fib(n):
         if n < 2: return n
         return fib(n-2) + fib(n-1)

t = Test()
t.fib(6)

------------------------
Traceback (most recent call last):
return fib(n-2) + fib(n-1)
NameError: name 'fib' is not defined
-------------------------



More information about the Python-list mailing list