在Python 3中正确使用全局变量

Ede*_*row 41 python variables function global-variables python-3.x

在Python 3中正确使用全局变量是什么?:

1)global VAR_NAME在核心脚本中说明一次(不在函数内),然后简单地将变量引用到VAR_NAME其他地方

2)global VAR_NAME在每个使用全局变量的函数中说明一次,然后简单地将函数引用到VAR_NAME函数的其余部分以及核心脚本本身内部

Len*_*bro 55

在第一种情况下,global关键字是没有意义的,因此这是不正确的.在模块级别定义变量使其成为全局变量,您不需要全局关键字.

第二个例子是正确的用法.

但是,全局变量的最常见用法是不在任何地方使用global关键字.仅当您要在函数/方法中重新分配全局变量时才需要global关键字.

  • downvoters可以解释这个答案有什么问题吗? (4认同)
  • 我不是反对,但我看到这个答案有一个问题:OP的#2示例实际上是不正确的:函数内不需要全局关键字,除非函数为全局变量分配[新]值。如果函数仅引用(读取)全局变量,则不需要 global 关键字。 (2认同)

Dan*_*son 46

如果以一种本来可以解释为局部变量赋值的方式使用全局变量,则需要在函数中使用global关键字.如果没有global关键字,您将创建一个隐藏函数范围内的全局变量的局部变量.

这里有一些例子:

global_var = 1

def example1():
    # global keyword is not needed, local_var will be set to 1.
    local_var = global_var

def example2():
    # global keyword is needed, if you want to set global_var,
    # otherwise you will create a local variable.
    global_var = 2

def example3():
    # Without using the global keyword, this is an error.
    # It's an attempt to reference a local variable that has not been declared.
    global_var += 1
Run Code Online (Sandbox Code Playgroud)


小智 6

"以某种方式将其解释为对局部变量的赋值"---是的,但这里有一个微妙的细节:

-------------------错误:赋值前引用的局部变量'c'

def work():
  c += 3

c = 0

work()
print(c)
Run Code Online (Sandbox Code Playgroud)

-------------------错误:赋值前引用的局部变量'c'

c = 0

def work():
  c += 3

work()
print(c)
Run Code Online (Sandbox Code Playgroud)

-------------------打印[3]

def work():
  c.append(3)

c = []

work()
print(c)
Run Code Online (Sandbox Code Playgroud)

-------------------打印[3]

c = []

def work():
  c.append(3)

work()
print(c)
Run Code Online (Sandbox Code Playgroud)