# 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
- 我没有在func函数中添加
global x
,但它仍然可以找到x
是50,为什么? - 当我在 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/