[Tutor] Global var problem
Nick Lunt
nick at javacat.f2s.com
Fri Oct 28 23:16:08 CEST 2005
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 .
More information about the Tutor
mailing list