Python函数中的全局变量?

19 浏览
0 Comments

Python函数中的全局变量?

这个问题已经有了答案

在函数中使用全局变量

我知道我应该避免使用全局变量,因为像这样的混淆,但如果我要使用它们,以下是使用它们的有效方法吗?(我正在尝试调用在单独的函数中创建的变量的全局副本。)

x = "somevalue"
def func_A ():
   global x
   # Do things to x
   return x
def func_B():
   x = func_A()
   # Do things
   return x
func_A()
func_B()

第二个函数使用的 x 的值是否与 func_a 使用并修改的全局副本的值相同?在定义后调用这些函数时,顺序是否重要?

admin 更改状态以发布 2023年5月23日
0
0 Comments

在Python作用域中,任何对于未在该作用域中声明的变量进行的赋值操作都会创建一个新的局部变量,除非在函数中先前声明了该变量作为一个关键字为global的具有全局作用域的变量引用。让我们看一下您伪代码的修改版本,看看会发生什么:

# Here, we're creating a variable 'x', in the __main__ scope.
x = 'None!'
def func_A():
  # The below declaration lets the function know that we
  #  mean the global 'x' when we refer to that variable, not
  #  any local one
  global x
  x = 'A'
  return x
def func_B():
  # Here, we are somewhat mislead.  We're actually involving two different
  #  variables named 'x'.  One is local to func_B, the other is global.
  # By calling func_A(), we do two things: we're reassigning the value
  #  of the GLOBAL x as part of func_A, and then taking that same value
  #  since it's returned by func_A, and assigning it to a LOCAL variable
  #  named 'x'.     
  x = func_A() # look at this as: x_local = func_A()
  # Here, we're assigning the value of 'B' to the LOCAL x.
  x = 'B' # look at this as: x_local = 'B'
  return x # look at this as: return x_local

实际上,您可以使用名为x_local的变量重新编写func_B中的所有内容,并且它将完全相同地工作。顺序只有在函数执行更改全局x值的操作的顺序方面才有所影响。因此,在我们的示例中,顺序并不重要,因为func_B调用func_A。在这个示例中,顺序确实很重要:

def a():
  global foo
  foo = 'A'
def b():
  global foo
  foo = 'B'
b()
a()
print foo
# prints 'A' because a() was the last function to modify 'foo'.

请注意,global仅需要修改全局对象。您仍然可以在函数内部访问它们而不声明global。因此,我们有:

x = 5
def access_only():
  return x
  # This returns whatever the global value of 'x' is
def modify():
  global x
  x = 'modified'
  return x
  # This function makes the global 'x' equal to 'modified', and then returns that value
def create_locally():
  x = 'local!'
  return x
  # This function creates a new local variable named 'x', and sets it as 'local',
  #  and returns that.  The global 'x' is untouched.

请注意create_locally和access_only之间的区别-access_only尽管没有调用global,但仍然访问全局x,而即使create_locally也没有使用global,但它创建了一个本地副本,因为它正在进行分配一个值。这里的混淆是您为什么不应该使用全局变量。

0
0 Comments

如果您只想访问全局变量,只需使用它的名称。但是,要更改它的值,您需要使用 global 关键字。

例如:

global someVar
someVar = 55

这将将全局变量的值更改为55。否则,它只会将55分配给局部变量。

函数定义列表的顺序并不重要(假设它们没有以某种方式相互引用),它们被调用的顺序则很重要。

0