Hi Nick,

Global variables in Python are global for *reading*, based in the 
precedence order for looking into the namespace: locals, globals(module 
scope actually), builtins

for writing, as variables are created on the fly, a local variable will 
be created and will mask the global one.

That's why the keyword global "exists"

Do:

global x

whenever there is a variable that you need to *modify*, and that already 
exists ourside the function.

In your example:


 > Now this
 > class T:
 >         def p(self):

                   global x
                   #this line brings x into existence for writing


 >                 x += 1
 >                 print x
 >
 > if __name__ == '__main__':
 >         x = 1
 >         t = T()
 >         t.p()
 >

You'll get rid of the exception and the error.

Hope it helps.

Hugo


Nick Lunt wrote:
> Hi Folks,
> 
> messing about with classes I've come across something basic that I don't 
> understand.
> 
> Take this class
> 
> class T:
>         def p(self):
>                 print x
> 
> if __name__ == '__main__':
>         x = 1
>         t = T()
>         t.p()
> 
> This outputs 1
> 
> Now this
> class T:
>         def p(self):
>                 x += 1
>                 print x
> 
> if __name__ == '__main__':
>         x = 1
>         t = T()
>         t.p()
> 
> This outputs
> UnboundLocalError: local variable 'x' referenced before assignment
> 
> So I tried this
> 
> class T:
>         def p(self):
>                 x += 1
>                 print x
> 
> if __name__ == '__main__':
>         global x
>         x = 1
>         t = T()
>         t.p()
> 
> but that gives me the same UnboundLocalError exception.
> 
> This has got me confused. Why does the first example work ok, but not 
> the second ?
> And in the third example I get the same error even after declaring x to 
> be global.
> 
> No doubt the answer is staring me in the face ... but I still can't see it.
> 
> Cheers
> Nick .
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to