如何在python函数中使用全局变量?

stg*_*rge 18 python global-variables

如何在python函数中设置全局变量?

Suk*_*lra 23

global在函数内部使用变量,您需要global <varName>在函数内部执行此操作.

testVar = 0

def testFunc():
    global testVar
    testVar += 1

print testVar
testFunc()
print testVar
Run Code Online (Sandbox Code Playgroud)

给出输出

>>> 
0
1
Run Code Online (Sandbox Code Playgroud)

请记住,global如果要进行分配/更改它们,您只需要在函数内声明它们.global打印和访问不需要.

你可以做,

def testFunc2():
    print testVar
Run Code Online (Sandbox Code Playgroud)

没有global像我们在第一个函数中那样声明它,它仍然会给出正确的值.

使用一个list例子,你不能在list没有声明的情况下指定它,global但你可以调用它的方法并更改列表.如下.

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.
Run Code Online (Sandbox Code Playgroud)