根据http://www.faqs.org/docs/diveintopython/fileinfo_private.html:
像大多数语言一样,Python具有
私有元素的概念:
私人
函数,这些函数不能被调用
在模块外
然而,如果我定义两个文件:
#a.py
__num=1
and:
#b.py
import a
print a.__num
当我运行b.py时,它输出1而不给出任何异常。是diveintopython错了,还是我误解了什么?是否有方法将模块的函数定义为私有?
In Python, "privacy" depends on "consenting adults'" levels of agreement - you can't force it (any more than you can in real life;-). A single leading underscore means you're not supposed to access it "from the outside" -- two leading underscores (w/o trailing underscores) carry the message even more forcefully... but, in the end, it still depends on social convention and consensus: Python's introspection is forceful enough that you can't handcuff every other programmer in the world to respect your wishes.
((顺便说一下,虽然这是一个严格保密的秘密,但对于c++来说也是如此:在大多数编译器中,在#包括你的.h文件之前,一个简单的#define private public line就可以让狡猾的编码器对你的“隐私”进行散列…!-))