python - 关于python中的global关键字

标签 python

# coding: utf-8

def func():
    print 'x is', x
    #x = 2   #if I add this line, there will be an error, why?
    print 'Changed local x to', x
x = 50
func()
print 'Value of x is', x 
  1. 我没有在func函数中添加global x,但它仍然可以找到x是50,为什么?
  2. 当我在 func 函数中添加 x=2 行时,会出现错误(UnboundLocalError: local variable 'x' referenced before assignment),为什么?

最佳答案

这里的技巧是静态检测本地名称:

  • 只要函数中没有分配名称x,对x 的引用就会解析到全局范围
  • 如果名称 x 在函数中分配到 anywhere ,Python 假定 x 因此是一个局部名称 everywhere 在函数中。因此,第一行变为错误,因为在分配之前使用了本地名称 x

换句话说:分配的名称在函数的任何地方都被视为局部的,而不仅仅是在分配点之后。

关于python - 关于python中的global关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10138937/

相关文章:

python - 创建二维字符串数组

python - 合并排序代码挂起

python - 使用 arcpy 以编程方式更新要素类的元数据

python - 调整图像大小,使其大小与指定的宽高比匹配

python - 如何在 Python 中获取父目录?

Python 读取文件并迭代它

python - 如何在Python中正确导入?

python - 获得所需数据后,如何关闭 Python 2.5.2 Popen 子进程?

python - 使用 beautifulsoup 从表单中提取隐藏值

python - 安装没有 pip/easy_install 或 "python setup.py install"的模块