[Tutor] Global var problem
Alan Gauld
alan.gauld at freenet.co.uk
Sat Oct 29 00:05:51 CEST 2005
> messing about with classes I've come across something basic that I don't
> understand.
As you say this has nothing to do with classes its more basic. Its about
namespaces. Try reading the namespaces topic in my tutor for more info.
Meanwhile lets simplify by removing the class bit
def f():
print x
def g():
x = x + 1 # expanded version of ++ shortcut
print x
x = 42
f() # prints 42
g() # gives an error
The error is because you are assigning to x thus creating a local var
of that name, but you are using x in the definition of x which doesn't
make any kind of sense
def h():
global x
x += 1
print x
h() # prints 43
HTH,
Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list