class Test{but if you think you can change a module level variable in Python, you are totally wrong.please see following:
private String x=null;//declare a new variable:x
public change_variable(){
x="hello" //change the outside variable inside the method
}
}
#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:
Post a Comment