[Tutor] Global var problem
w chun
wescpy at gmail.com
Sat Oct 29 00:22:03 CEST 2005
> if __name__ == '__main__':
> global x
> x = 1
> t = T()
> t.p()
as alan mentioned, it's all about namespaces. the "global x" you have
in the above piece of code doesn't do anything (because you're already
or still in the global [name]space).
you're getting the error in your p() method because there is an
assignment to x in there. when that happens, it's part of p's local
namespace. during compilation, the interpreter sees this creation of
a local name, but because you access it before you assign it, i.e., x
= x + 1, you get that error.
add your global request to p(), and you'll be fine:
def p(self):
global x
x += 1
print x
hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2006,2001
http://corepython.com
wesley.j.chun :: wescpy-at-gmail.com
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
More information about the Tutor
mailing list