命名空间(namespaces),在研究类或者面向对象编程中,它常常
被提到。虽然在函数那部分已经对命名空间有初步解释,但那是在函数
的知识范畴中的理解。现在,我们在类的知识范畴中理解“类命名空
间”——定义类时,所有位于class语句中的代码都在某个命名空间中执
行,即类命名空间。
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!
命名空间因为对象的不同也有所区别,可以分为如下几种。
(1)内置命名空间(Built-in Namespaces):Python运行起来,它
们就存在了。内置函数的命名空间都属于内置命名空间,所以,我们可
以在任何程序中直接运行它们,比如前面的id(),不需要做什么操作,
拿过来就能直接使用。
(2)全局命名空间(Module:Global Namespaces):每个模块创建
它自己所拥有的全局命名空间,不同模块的全局命名空间彼此独立,不
同模块中相同名称的命名空间,也会因为模块的不同而不相互干扰。
(3)本地命名空间(Function&Class:Local Namespaces):模块中
有函数或者类,每个函数或者类所定义的命名空间就是本地命名空间。
如果函数返回了结果或者抛出异常,则本地命名空间也结束了。