2013-02-26 93 views
4

我是Python新手, ,並開始編寫其他人編寫的代碼。導入__module__ python:爲什麼下劃線?

在一封來自PyPI下載軟件包的來源我已經注意到使用

import __module__ 

使用在包裝的src文件夾中定義的函數和類。

這是常見的做法嗎?我實際上無法真正理解這種語法, 你能解釋給我還是寄給我一些參考?

+1

包中實際上是否有一個名爲'__module __。py'的文件? – 2013-02-26 14:37:00

回答

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,而只是用這種風格命名了一些對象,因爲他們認爲它看起來很酷或者更重要。

+0

..我仍然不明白爲什麼我應該使用導入'__module__'來包含來自src文件夾的代碼,儘管... – lucacerone 2013-02-26 14:05:32

+1

那麼如果您命名* your * module'__helloWorld__',那麼它將如何被導入爲好。不過,這不是堅持半官方風格指南PEP8。 – Junuxx 2013-02-26 14:12:58