[Tutor] Why thus?

Christian Tismer tismer@tismer.com
Sun, 12 Mar 2000 23:26:43 +0100


"Wesley J. Chun" wrote:
> 
>     > Date: Sun, 12 Mar 2000 22:29:57 +0100
>     > From: Christian Tismer <tismer@tismer.com>
>     >
>     > The difference is: When compiling your code, the compiler
>     > tries to figure out what is global and what not. Since
>     > counter is assigned to, it becomes a local. But the object
>     > does not yet exist when you request it:
>     >    counter=counter+1
>     > wants to retrieve the current value, and it isn't set yet.
>     > You are accessing a local variable which already has its
>     > slot and is ready to receive a value, but cannot until
>     > it is initialized.
> 
> chris is absolutely right.  when doing an assignment in a
> local scope, the compiler will search only for the local
> name, and since you haven't done a "counter = XXX" within
> __init__(), it will complain.

Careful, in his exmple he wasn't referring to self
at all, and __init__() wouldn't have helped.

> # this fails (references local var that hasn't been
> #               assigned/doesn't exist)
> i = 4
> def foo():
>     print i   # "print global 'i'"
++++++++++++++++++++++++ local
>     i = 6     # set local 'i'
> 
> the result is a "NameError: i".  upon seeing the presence
> of a local 'i' makes any previous code *think* it should
> access a local 'i' vs. the global one.

+++Please try to avoid false comments, this confuses
people who are not already sure what's right and what not.

Short conclusion: A name in a function is either local
or global. If it is assigned to, it is local, unless
spelled in a "global" statement. Non-assigned names
are always global.

...

> "Core Python Programming", Prentice-Hall, TBP Summer 2000
> (will have an example like this in here too!)

Also "Learning Python" can be recommended (not only because
I translated it into German :-)

ciao - chris

-- 
Christian Tismer             :^)   <mailto:tismer@appliedbiometrics.com>
Applied Biometrics GmbH      :     Have a break! Take a ride on Python's
Kaunstr. 26                  :    *Starship* http://starship.python.net
14163 Berlin                 :     PGP key -> http://wwwkeys.pgp.net
PGP Fingerprint       E182 71C7 1A9D 66E9 9D15  D3CC D4D7 93E2 1FAE F6DF
     we're tired of banana software - shipped green, ripens at home