在test,我们第一次赋值给x的时候创建了变量,然后后面又改变了变量x,如果x是全局变量时,就会如下:
x='e f t efdad'
def test():
print(x)
print(id(x))
#x=123
#print(x)
#print(id(x))
if __name__=='__main__':
test()
但是,我们需要注意一点,看见上面代码里面的注释没有,如果注释放开了,他就会报错了,为什么?
x='e f t efdad'
def test():
print(x)
print(id(x))
x=123
print(x)
print(id(x))
if __name__=='__main__':
test()
输出:
>>> ================================ RESTART ================================
>>>
Traceback (most recent call last):
File "C:\Python34\test.py", line 9, in <module>
test()
File "C:\Python34\test.py", line 3, in test
print(x)
UnboundLocalError: local variable 'x' referenced before assignment
>>>
没有找到本地变量x,我认为是这样的,虽然py是解释性的语言,但是他还是需要编译成pyc文件来执行,只不过这个过程我们看不见,在编译的过程中x其实已经被认定为本地变量,而不再是模块里面的全局变量,所以才会出现这种情况,那么怎么解决?我们只需要在改动x前面加上global x即可,global关键字我们下面的章节会详细讲述
x='e f t efdad'
def test():
print(x)
print(id(x))
global x
x=123
print(x)
print(id(x))
if __name__=='__main__':
test()
输出:
>>> ================================ RESTART ================================
>>>
e f t efdad
31843176
123
505993584
>>>