我是Python新手, ,并开始编写其他人编写的代码。导入__module__ python:为什么下划线?
在一封来自PyPI下载软件包的来源我已经注意到使用
import __module__
使用在包装的src
文件夹中定义的函数和类。
这是常见的做法吗?我实际上无法真正理解这种语法, 你能解释给我还是寄给我一些参考?
我是Python新手, ,并开始编写其他人编写的代码。导入__module__ python:为什么下划线?
在一封来自PyPI下载软件包的来源我已经注意到使用
import __module__
使用在包装的src
文件夹中定义的函数和类。
这是常见的做法吗?我实际上无法真正理解这种语法, 你能解释给我还是寄给我一些参考?
这是一些内置对象的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,而只是用这种风格命名了一些对象,因为他们认为它看起来很酷或者更重要。
..我仍然不明白为什么我应该使用导入'__module__'来包含来自src文件夹的代码,尽管... – lucacerone 2013-02-26 14:05:32
那么如果您命名* your * module'__helloWorld__',那么它将如何被导入为好。不过,这不是坚持半官方风格指南PEP8。 – Junuxx 2013-02-26 14:12:58
包中实际上是否有一个名为'__module __。py'的文件? – 2013-02-26 14:37:00