一,引言
现在我有个问题,函数里面的变量,在函数外面能直接引用么?
deffunc1():
m= 1
print(m)print(m) #这行报的错
报错了:
NameError: name'm' is not defined
上面为什么会报错呢?现在我们来分析一下python内部的原理是怎么样:
我们首先回忆一下Python代码运行的时候遇到函数是怎么做的,从Python解释器开始执行之后,就在内存中开辟里一个空间,每当遇到一个变量的时候,就把变量名和值之间对应的关系记录下来,但是当遇到函数定义的时候,解释器只是象征性的将函数名读如内存,表示知道这个函数存在了,至于函数内部的变量和逻辑,解释器根本不关心。
等执行到函数调用的时候,Python解释器会再开辟一块内存来储存这个函数里面的内容,这个时候,才关注函数里面有哪些变量,而函数中的变量回储存在新开辟出来的内存中,函数中的变量只能在函数内部使用,并且会随着函数执行完毕,这块内存中的所有内容也会被清空。
我们给这个‘存放名字与值的关系’的空间起了一个名字-------命名空间。
代码在运行伊始,创建的存储“变量名与值的关系”的空间叫做全局命名空间;
在函数的运行中开辟的临时的空间叫做局部命名空间。
二,命名空间和作用域
>>> importthis
The Zen of Python, by Tim Peters
Beautifulisbetter than ugly.
Explicitisbetter than implicit.
Simpleisbetter than complex.
Complexisbetter than complicated.
Flatisbetter than nested.
Sparseisbetter than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should neverpasssilently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way maynot be obvious at fi