【问题标题】:Accessing global variable in function in python在python中访问函数中的全局变量
【发布时间】:2018-01-22 19:17:39
【问题描述】:

我有两段代码:

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

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

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

UnboundLocalError: local variable 'x' referenced before assignment

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

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

【问题讨论】:

标签: python-3.x global-variables local-variables


【解决方案1】:
# 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)

【讨论】:

    【解决方案2】:

    正如艾文所说,也可以这样修改代码:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多