在python中定义私有模块函数 [英] Defining private module functions in python
问题描述
根据 http://www.faqs.org/docs/diveintopython/fileinfo_private。 html :
与大多数语言一样,Python具有私有元素的
概念:
- 私人
功能,无法从
模块外调用
但是,如果我定义了两个文件:
#a.py
__num = 1
和
#b.py
导入a b $ b打印a .__ num
当我运行 b.py
时,它打印出 1
没有给出任何例外。 diveintopython错了吗,还是我误解了一些东西?有什么方法可以 do 将模块的函数定义为private?
#define private public $ c #include
您的 .h
文件中的$ c>行是w code编码器对您的散列privacy...! - )) According to http://www.faqs.org/docs/diveintopython/fileinfo_private.html:
Like most languages, Python has the concept of private elements:
- Private functions, which can't be called from outside their module
However, if I define two files:
#a.py
__num=1
and:
#b.py
import a
print a.__num
when i run b.py
it prints out 1
without giving any exception. Is diveintopython wrong, or did I misunderstand something? And is there some way to do define a module's function as private?
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.
((Btw, though it's a closely held secret, much the same holds for C++: with most compilers, a simple #define private public
line before #include
ing your .h
file is all it takes for wily coders to make hash of your "privacy"...!-))
这篇关于在python中定义私有模块函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!