Le 27/09/2019 à 14:26, Jan van den Broek a écrit :
On 2019-09-27, ast <n...@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
--
https://mail.python.org/mailman/listinfo/python-list