Sunday, November 23, 2008

The global statement

Today I want to talk about the global statement in Python.Since I'm a java programmer,so I usually like to compare the difference between python and java.Now I want to talk about the global statement.In Java all stuff placed into a class file,so if you want to change a class level variable in a method,you can simply assign a new value to this variable.for example:
class Test{
private String x=null;//declare a new variable:x
public change_variable(){
x="hello" //change the outside variable inside the method
}
}
but if you think you can change a module level variable in Python, you are totally wrong.please see following:
#python code
x=99 #this is a global variable
#define a function
def func():
x=100

func() #call this function
print x # what's happened? x=99 or x=100

#the truth is x=99


Why is that,because when you use a same variable name in the function,Python will create a new local variable instead of use the global variable,so the global x is not changed.Then,if you really want to change the global variable,you must use the global keyword:
#python code
x=99 #this is a global variable
#define a function
def func():
global x #now it seems as we declare that we'll use the global x
x=100

func() #call this function
print x # what's happened? x=99 or x=100

#now x=100

No comments: