Recursive method in class

Anders Märak Leffler anders.marak.leffler at gmail.com
Mon Sep 30 07:11:24 EDT 2019


What do you mean by transformed? This is probably your understanding
already, but a further consequence of when arguments are evaluated
plus what you said about data attributes is that the fib(self, n - 1)
call will follow the standard LEGB-lookup of whatever "fib" is, from
the point of view of the function object. As far as I know, there is
no transformation of these scopes - either when it comes to creating
the class, or creating the instances. (self is just the instance,
passed as an argument.)

Cf when you change a binding:

>>> def factorial(self, n):
...     if not n:
...             return 1
...     else:
...             return n * factorial(self, n - 1)
...
>>> Dummy = type("DummyObject", (object, ), {"factorial" : factorial})
>>> instance = Dummy()
>>> def factorial(self, n):
...     print("Hello!")
...     return 999
...
>>> instance.factorial(5)   # Where will the call go ("old" or "new" factorial?)? Where will possible recursive calls go (and why)?
Hello!
4995

Oh, and as others have pointed out on this list - you/whoever runs the
system sending the mail might want to change the return address.
none at gmail.com is somewhat consistently classed as spam.



//Anders

PS. We could further complicate this by adding a call to
self.factorial in the new function, but let's not go there. :)


On Mon, Sep 30, 2019 at 9:58 AM ast <none at gmail.com> wrote:
>
> 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
> --
> https://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list