Recursive method in class

ast none at gmail.com
Mon Sep 30 03:53:18 EDT 2019


Le 27/09/2019 à 14:26, Jan van den Broek a écrit :
> On 2019-09-27, ast <none at gmail.com> wrote:
>> 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)
>                    self.fib(...)
> 
> [Schnipp]
> 

Yes you are right. I forgot that class methods
don't see class attributes

An other workaround:

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

It comes from https://www.pythonsheets.com/notes/python-object.html

 >>> def fib(self, n):
...     if n <= 2:
...         return 1
...     return fib(self, n-1) + fib(self, n-2)
...
 >>> Fib = type('Fib', (object,), {'val': 10,
...                               'fib': fib})
 >>> f = Fib()
 >>> f.val
10
 >>> f.fib(f.val)
55

So it means that when classes are constructed explicitely
with type(name, bases, dict_), some methods are transformed



More information about the Python-list mailing list