您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

global函数内部使用变量,您需要global <varName>像这样在函数内部进行操作。

testVar = 0

def testFunc():
    global testVar
    testVar += 1

print testVar
testFunc()
print testVar

给出输出

>>> 
0
1

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

你可以做,

def testFunc2():
    print testVar

global不像我们在第一个函数中那样声明它,它仍然可以正确赋值。

以alist为例,您不能在list不声明的情况下分配a ,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.
python 2022/1/1 18:42:24 有284人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶