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

发布于 2021-01-29 19:07:19

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

关注者
0
被浏览
119
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    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.
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看