Need help with Python scoping rules
Hendrik van Rooyen
hendrik at microcorp.co.za
Thu Aug 27 03:09:21 EDT 2009
On Wednesday 26 August 2009 17:45:54 kj wrote:
> In <02a54597$0$20629$c3e8da3 at news.astraweb.com> Steven D'Aprano
<steve at REMOVE-THIS-cybersource.com.au> writes:
> >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.
If the sole purpose of the function is to be used to define what will become a
constant, why do you not just calculate the constant on your calculator, or
at the interactive prompt, and assign it to the attribute, and be done with
it?
Why waste run time recalculating every time the programme is called?
>
> 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".
Why *must* it be there?
>
> 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.
Seems no point to me even when there is recursion - a number is a number is a
number. If you know the arguments when you write it, and if the function is
known at time of writing, storing a literal is the best solution.
Conversely, if the arguments are not known at time of writing, then they
should be passed at run time, when an instance is created, and assigned as
part of the __init__ method.
And the same is true if the function is not known at time of writing - then it
must be passed to the constructor of the instance.
Storm in a teacup.
- Hendrik
More information about the Python-list
mailing list