在python中定义私有模块函数 [英] Defining private module functions in python

查看:291
本文介绍了在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?

在Python中, 隐私取决于同意成年人的协议级别 - 你不能强迫它(比现实生活中的任何更多;-)。一个主要的下划线意味着你不是假设从外部访问它 - 两个前导下划线(没有尾随下划线)更强有力地传递消息......但最终还是取决于社会惯例和共识:Python的内省足够强大,以至于你无法手铐每个其他程序员都会尊重你的愿望。

(btw,尽管它是一个密码保守的秘密,对于C ++来说也是如此:对于大多数编译器,简单的 #define private public #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 #includeing your .h file is all it takes for wily coders to make hash of your "privacy"...!-))

这篇关于在python中定义私有模块函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆