在 python 中访问函数中的全局变量

Accessing global variable in function in python

我有两段代码:

def g(y):
  print(x)
x = 5 
g(x)

def h(y):
  x = x + 1
x = 5
h(x)

第一段代码可以完美打印“5”,而第二段代码 returns:

UnboundLocalError: local variable 'x' referenced before assignment

这到底是什么意思?它是否试图说它试图在评估行 x=5 之前评估行 x = x + 1?如果是这样,为什么第一段代码没有产生任何错误?它同样必须在 x 被赋值之前评估行 print(x)

我想我可能对函数的调用方式有误解。但是我不知道我错了什么。

# first block: read of global variable. 
def g(y):
  print(x)
x = 5 
g(x)

# second block: create new variable `x` (not global) and trying to assign new value to it based on on this new var that is not yet initialized.
def h(y):
  x = x + 1
x = 5
h(x)

如果您想使用全局,您需要使用 global 关键字明确指定:

def h(y):
  global x
  x = x + 1
x = 5
h(x)

正如Aiven所说,或者你可以这样修改代码:

def h(y):
   x = 9
   x = x + 1
   print(x) #local x
x = 5
h(x)
print(x) #global x