How do I set a global variable inside of a python function?
解决方案
To use global variables inside a function, you need to do global inside the function, like so.
testVar = 0
def testFunc():
global testVar
testVar += 1
print testVar
testFunc()
print testVar
gives the output
>>>
0
1
Keep in mind, that you only need to declare them global inside the function if you want to do assignments / change them. global is not needed for printing and accessing.
You can do,
def testFunc2():
print testVar
without declaring it global as we did in the first function and it'll still give the value all right.
Using a list as an example, you cannot assign a list without declaring it global but you can call it's methods and change the list. Like follows.
testVar = []
def testFunc1():
testVar = [2] # Will create a local testVar and assign it [2], but will not change the global variable.
def testFunc2():
global testVar
testVar = [2] # Will change the global variable.
def testFunc3():
testVar.append(2) # Will change the global variable.