Python function global variables?

前端 未结 6 734
广开言路
广开言路 2020-11-22 04:49

I know I should avoid using global variables in the first place due to confusion like this, but if I were to use them, is the following a valid way to go about using them? (

6条回答
  •  有刺的猬
    2020-11-22 05:30

    You can directly access a global variable inside a function. If you want to change the value of that global variable, use "global variable_name". See the following example:

    var = 1
    def global_var_change():
          global var
          var = "value changed"
    global_var_change() #call the function for changes
    print var
    

    Generally speaking, this is not a good programming practice. By breaking namespace logic, code can become difficult to understand and debug.

提交回复
热议问题