Need help with Python scoping rules
zuo at chopin.edu.pl
Wed Aug 26 23:54:16 CEST 2009
26-08-2009 o 17:45:54 kj <no.email at please.post> wrote:
> 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
>>> 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.
1. I don't understand then... Why do you desire to both define and
run it *within* that class statement as if it was this class's
2. Could you please show me how it could be done in C++ or Java?
(Or you want to say that that languages also are not fully valuable
3. Python makes function bodies "agnostic" about the context of their
definition -- generally any non-global information must be passed
explicitly to their interior. *It has nothing to do with recursion.*
If you really must both define and use such a function within the
class definition, pass function object to itself explicitly, and
everybody will be happy:
def fact(fact, n):
if n < 2:
return n * fact(fact, n - 1)
Jan Kaliszewski (zuo) <zuo at chopin.edu.pl>
More information about the Python-list