4

我是 Python 新手,已经开始编写其他人编写的代码。

在从 Pypi 下载的包的源代码中,我注意到使用

import __module__

src使用包文件夹中定义的函数和类。

这是常见的做法吗?我实际上无法真正理解这种语法,你能给我解释一下或给我一些参考吗?

4

1 回答 1

6

这是一些内置对象的 python 约定。从 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,只是以这种风格命名了一些对象,因为他们认为它看起来很酷或更重要。

于 2013-02-26T13:53:39.230 回答