Question about scope
Carsten Gaebler
clpy at snakefarm.org
Thu Jul 5 17:27:59 EDT 2001
Tim Daneliuk wrote:
> I guess what I want to know is when globally declared objects are seen inside a function, class, or
> block, and when they must be explicitly declared as being global.
You can always 'read' a global variable in a function, e.g.
g = 0
def func():
print g
func()
prints '0'. If you want to modify a global variable inside a function you
need to declare it as global:
g = 0
def func():
global g
g = 1
func()
print g
prints '1'.
Otherwise an assignment inside a function will create a new variable in
the local namespace:
g = 0
def func():
g = 1
print g
prints '0' because g=1 only exists inside func().
Hope it helps.
cg.
More information about the Python-list
mailing list