我是Python新手, 并开始研究其他人编写的代码。
在从Pypi下载的软件包源代码中,我注意到了
的使用import __module__
使用包的src
文件夹中定义的函数和类。
这是常见做法吗?我实际上无法真正理解这种语法, 你可以向我解释一下还是给我一些参考?
答案 0 :(得分:5)
这是一些内置对象的python约定。 From PEP8:
__double_leading_and_trailing_underscore__
:生活在用户控制的命名空间中的“神奇”对象或属性。例如。__init__
,__import__
或__file__
。不要发明这样的名字;只能按照文件记录使用它们。
但最终它不是一种理解与否的“语法”,__module__
只是一个带有下划线的名称。它与module
不同,完全无关。
一个示例向您展示它只是一个名称:
>>> __foo__ = 42
>>> print foo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined
>>> print _foo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '_foo' is not defined
>>> print __foo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '__foo' is not defined
>>> print __foo__
42
>>> type(__foo__)
<type 'int'>
没有什么特别之处。
如果没有关于你在哪里看到这个的更多信息,很难说出作者的意图是什么。他们要么导入一些python内置函数(例如from __future__ import...
),要么他们忽略了PEP8并且只是用这种风格命名了一些对象,因为他们认为它看起来很酷或更重要。