命名空间和作用域

  程序运行时,遇到全局变量时,会在内存开辟一块空间,将变量与其值的内存地址的关系,存入此空间,这个空间称为全局内存空间
  程序调用函数时,遇到函数的变量,会在内存中再开辟一块临时空间,存放函数中变量与其值的内存地址的关系,这种变量成为局部变量,这块临时空间成为局部名称空间。
加载顺序
  程序有很多内置的函数,方法,关键字,程序运行前,会开辟一块内置名称空间,将内置变量加载到内存中,程序运行时会开辟全局名称空间,存储遇到的全局变量与其值的内存地址的关系,调用函数时,会开辟一块临时空间,存放函数的变量与其值的内存地址的关系

 

命名空间和作用域
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
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 may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

python之禅
命名空间和作用域
python之禅

在python之禅中提到过:命名空间是一种绝妙的理念,让我们尽情的使用发挥吧!

命名空间一共分为三种:

  全局命名空间

  局部命名空间

  内置命名空间

*内置命名空间中存放了python解释器为我们提供的名字:input,print,str,list,tuple...它们都是我们熟悉的,拿过来就可以用的方法。

三种命名空间之间的加载与取值顺序:

加载顺序:内置命名空间(程序运行前加载)->全局命名空间(程序运行中:从上到下加载)->局部命名空间(程序运行中:调用时才加载)

取值顺序:

  在局部调用:局部命名空间->全局命名空间->内置命名空间

  在全局调用:全局命名空间->内置命名空间

综上所述,在找寻变量时,从小范围,一层一层到大范围去找寻。

作用域

作用域就是作用范围,按照生效范围可以分为全局作用域和局部作用域。

全局作用域:包含内置名称空间、全局名称空间,在整个文件的任意位置都能被引用、全局有效

局部作用域:局部名称空间,只能在局部范围生效

globals和locals方法

print(globals())
print(locals())
在全局调用globals和locals

相关文章: