[Tutor] Why thus?

Wesley J. Chun wesc@alpha.ece.ucsb.edu
Tue, 14 Mar 2000 14:15:38 -0800 (PST)


    > From tismer@tismer.com Sun Mar 12 14:26 PST 2000
    > 
    > "Wesley J. Chun" wrote:
    > > 
    > > 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.

right.  i meant to say that you haven't done set counter, i.e.
"counter = XXX", within your function (whether it's __init__()
or any other one).

    > 
    > > # 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'
    > > 
    > +++Please try to avoid false comments, this confuses
    > people who are not already sure what's right and what not.


sorry everyone.  i thought that if i put it in "double quotes"
you would see that *that* was the intention of the errorneous
programmer:  they *wanted* to access a global 'i', but sadly,
that is not the case.  what is really happening is that they
were accessing a local variable that didn't exist yet, so:

    i = 4
    def foo():
	print i   # print (uninitialized) local 'i'
	i = 6     # set local 'i'

as others have already suggested, adding 'global i' will solve
your problem.

hope this helps!!

-wesley

"Core Python Programming", Prentice-Hall, TBP Summer 2000

wesley.j.chun :: wesc@alpha.ece.ucsb.edu
cyberweb.consulting :: silicon.valley, ca
http://www.roadkill.com/~wesc/cyberweb/