Correct Use Of Global Variables In Python 3

后端 未结 4 1833
故里飘歌
故里飘歌 2020-12-12 20:48

Which is the correct use of global variables in Python 3?:

1) Stating global VAR_NAME once in the core script (not within a function) and then simply re

4条回答
  •  一整个雨季
    2020-12-12 20:58

    "in a way that would otherwise be interpreted as an assignment to a local variable" --- yes, but here is a subtle detail:

    ------------------- error: local variable 'c' referenced before assignment

    def work():
      c += 3
    
    c = 0
    
    work()
    print(c)
    

    ------------------- error: local variable 'c' referenced before assignment

    c = 0
    
    def work():
      c += 3
    
    work()
    print(c)
    

    ------------------- prints [3]

    def work():
      c.append(3)
    
    c = []
    
    work()
    print(c)
    

    ------------------- prints [3]

    c = []
    
    def work():
      c.append(3)
    
    work()
    print(c)
    

提交回复
热议问题