在python中定义私有模块函数

2024-03-29 12:45:00 发布

您现在位置:Python中文网/ 问答频道 /正文

根据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

但是,如果我定义了两个文件:

#a.py
__num=1

以及:

#b.py
import a
print a.__num

当我运行b.py时,它会打印出1,没有任何异常。是diveintopython错了,还是我误解了什么?是否有办法将模块的功能定义为私有的?


Tags: pyorghttpdocsmost定义htmlwww
3条回答

这个问题没有得到完全的回答,因为模块隐私并不是纯传统的,而且由于使用import可能会或可能不会识别模块隐私,这取决于它是如何使用的。

如果在模块中定义私有名称,则这些名称将被导入到使用语法“import module_name”的任何脚本中。因此,假设您在示例中正确地定义了模块private,_num,in a.py,like so。。

#a.py
_num=1

…您可以在b.py中使用模块名符号访问它:

#b.py
import a
...
foo = a._num # 1

要仅从a.py导入非私有项,必须使用from语法:

#b.py
from a import *
...
foo = _num # throws NameError: name '_num' is not defined

但是,为了清楚起见,在从模块导入名称时最好是显式的,而不是全部用“*”导入它们:

#b.py
from a import name1 
from a import name2
...

类私有化和模块私有化之间可能存在混淆。

A模块private以一个下划线开头 当使用import命令的from <module_name> import *形式时,这样的元素不会被复制;但是,如果使用import <moudule_name>语法(see Ben Wilhelm's answer
只需从问题示例的a.\u num中删除一个下划线,它就不会显示在使用from a import *语法导入a.py的模块中。

A类private两个下划线开始(也称为d under,即d-ouble under score)
这样的变量的名称“mangled”包括类名等。
它仍然可以通过损坏的名称在类逻辑之外访问。
尽管名称管理可以作为防止未经授权访问的一种温和的预防设备,但它的主要目的是防止可能与祖先类的类成员发生名称冲突。 见Alex Martelli有趣但准确地引用了同意成人,因为他描述了关于这些变量的惯例。

>>> class Foo(object):
...    __bar = 99
...    def PrintBar(self):
...        print(self.__bar)
...
>>> myFoo = Foo()
>>> myFoo.__bar  #direct attempt no go
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Foo' object has no attribute '__bar'
>>> myFoo.PrintBar()  # the class itself of course can access it
99
>>> dir(Foo)    # yet can see it
['PrintBar', '_Foo__bar', '__class__', '__delattr__', '__dict__', '__doc__', '__
format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__
', '__subclasshook__', '__weakref__']
>>> myFoo._Foo__bar  #and get to it by its mangled name !  (but I shouldn't!!!)
99
>>>

在Python中,“隐私”取决于“同意的成年人”的同意程度-你不能强迫它(比你在现实生活中所能做的任何事情都多;-)。一个前导下划线意味着您不应该从“外部”访问它--两个前导下划线(不带尾随下划线)更有力地承载消息。。。但是,归根结底,这仍然取决于社会惯例和共识:Python的自省足够有力,以至于你不能给世界上其他程序员戴上手铐来尊重你的意愿。

((btw),尽管它是一个紧密持有的秘密,但对于大多数C++编译器来说是一样的:对于大多数编译器,在{{{CD2}}之前的一个简单的^ {CD1>}行是您的^ {< CD3>}文件,这是狡猾的编码器所要做的“隐私”的散列所需要的一切……-))

相关问题 更多 >