osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Recursive method in class


On 01/10/2019 08:37, ast wrote:
> I understood your example, but it doesn't answer my initial question.
> I try to rewrite my question:
> 
> The following code is working well and I don't really understand why
> 
> def factorial(self, n):
>  ??? if not n:
>  ??????? return 1
>  ??? else:
>  ??????? return n * factorial(self, n - 1)
> 
> Dummy = type("DummyObject", (object, ), {"factorial" : factorial})
> instance = Dummy()
> instance.factorial(3)
> 
> 6? # correct
> 
> The problem is that "factorial" in line
> "return n * factorial(self, n - 1)" should not have been found
> because there is no factorial function defined in the current
> scope.

Not so.  "factorial" is in the global scope of your module, which is 
always available.

> 
> if you use "class" keyword to define the class
> 
> class Dummy:
> 
>  ??? def factorial(self, n):
>  ??????? if not n:
>  ??????????? return 1
>  ??????? else:
>  ??????????? return n * factorial(self, n - 1)
> 
> instance = Dummy()
> instance.factorial(3)
> 
> It generate an error because "factorial" in line
> "return n * factorial(self, n - 1)" is not found.
> 
> Traceback (most recent call last):
>  ? File "<pyshell#42>", line 1, in <module>
>  ??? instance.factorial(3)
>  ? File "<pyshell#40>", line 7, in factorial
>  ??? return n * factorial(self, n - 1)
> NameError: name 'factorial' is not defined
> 
> This is OK to me

Here, "factorial" is *not* in scope.  It's an attribute of the Dummy 
class, which is in scope, so you have to access it via Dummy (or more 
usually "self", because "self" is an instance of Dummy so has access).

> 
> The correct way is to write:
> 
> class Dummy:
> 
>  ??? def factorial(self, n):
>  ??????? if not n:
>  ??????????? return 1
>  ??????? else:
>  ??????????? return n * self.factorial(n - 1)
> 
> instance = Dummy()
> instance.factorial(3)
> 
> 6 # correct
> 
> So, to summarize, if you create a class with type(name, bases, dict_)
> or with the "class" keyword, recursive methods can't be writen
> in the same way. This is what puzzle me.

On the contrary, recursive methods are written in exactly the same way. 
What you aren't getting at the moment is what scope names exist in.

-- 
Rhodri James *-* Kynesim Ltd