A newbie quesiton: local variable in a nested funciton

jfong at ms4.hinet.net jfong at ms4.hinet.net
Sat Dec 26 04:07:20 EST 2015


Chris Angelico at 2015/12/26  UTC+8 11:44:21AM wrote:
> Pike is semantically very similar to Python, but it uses C-like
> variable scoping. Here's an equivalent, which might help with
> comprehension:
> 
> function outerf()
> {
>     int counter = 55;
>     void innerf()
>     {
>         write("%d\n", counter);
>         int counter;
>         counter += 1;
>     }
>     return innerf;
> }
Hi! ChrisA, this is the first time I hear the name "Pike" programming language:-)

> Based on that, I think you can see that having a variable declaration
> in the function turns things into nonsense. What you're actually
> wanting here is to NOT have the "int counter;" line, such that the
> name 'counter' refers to the outerf one.
> 
> In Python, assignment inside a function creates a local variable,
> unless you declare otherwise. To make your example work, all you need
> is one statement:
> 
> nonlocal counter
> 
> That'll cause the name 'counter' inside innerf to refer to the same
> thing as it does in outerf.

Thank you for the explanation. It reminds me to dig out something which seems I had been read before. It's about nested scope in the book "Learning Python" by Mark Lutz.

 "An assignment (X = value) creates or changes the name X in the current local
scope, by default. If X is declared global within the function, the assignment creates or changes the name X in the enclosing module's scope instead. If, on the other hand, X is declared  nonlocal within the function in 3.X (only), the assignment changes the name X in the closest enclosing function's local scope."

I shouldn't forget this:-(
 
> Hope that helps!

You have a correct answer. Thanks again.

--Jach



More information about the Python-list mailing list