Need help with Python scoping rules

kj no.email at please.post
Wed Aug 26 11:45:54 EDT 2009


In <02a54597$0$20629$c3e8da3 at news.astraweb.com> Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> writes:

>On Wed, 26 Aug 2009 10:57:32 +0000, kj wrote:

>> Recursion!  One of the central concepts in the theory of
>> functions!  This is shown most clearly by the following elaboration of
>> my original example:
>> 
>> class Demo(object):
>>     def fact_rec(n):
>>         if n < 2:
>>             return 1
>>         else:
>>             return n * fact_rec(n - 1)

>Why are you defining a method without a self parameter?

Because, as I've explained elsewhere, it is not a method: it's a
"helper" function, meant to be called only once, within the class
statement itself.

Well, this is not strictly true, because the function is recursive,
so it will also call itself a few times.  But still, all these
calls happen (loosely speaking) "within the class statement".

In fact the only reason to use a function for such initialization
work is when one needs recursion; otherwise there's no point in
defining a function that will only be invoked exactly once.

kynn



More information about the Python-list mailing list