osdir.com


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

Recursive method in class


On 10/1/2019 3:37 AM, ast wrote:

> 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)

This creates a function that looks up 'factorial' in the global (module) 
scope when called.

> Dummy = type("DummyObject", (object, ), {"factorial" : factorial})

This creates a reference to the function in the class dict.  There is 
now one function object with 2 references.

> instance = Dummy()
> instance.factorial(3)

instance.factorial still looks up 'factorial' in the global scope, and 
finds it there.  If you delete the global reference after creating the 
class, the lookup will fail, as when


> 
> 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.

Yes there is.  the 'current' scope always includes globals, and globals 
has a reference to the function.


-- 
Terry Jan Reedy