2015-12-17 44 views
2

我爲一個Python 3項目中vehicle.py是主要的腳本和文件夾stats以下文件夾結構被視爲一個包含幾個模塊:導入功能從Python 3個的模塊

enter image description here

cars模塊定義瞭如下功能:

def neon(): 
    print('Neon') 
    print('mpg = 32') 


def mustang(): 
    print('Mustang') 
    print('mpg = 27') 

使用Python 3,我可以從vehicle.py內訪問的功能的每個模塊中的FO llows:

import stats.cars as c 

c.mustang() 

然而,我想直接訪問每一個模塊中定義的功能,但我收到錯誤時做此:

import stats as st 

st.mustang() 
# AttributeError: 'module' object has no attribute 'mustang' 

我還試圖放置__init__.py文件中的stats用下面的代碼文件夾:

from cars import * 
from trucks import * 

,但我仍然收到錯誤:

import stats as st 

st.mustang() 
# ImportError: No module named 'cars' 

我試圖使用相同的方法與NumPy如:

import numpy as np 

np.arange(10) 
# prints array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) 

我怎麼能直接在模塊建立在Python 3包像NumPy的訪問功能?

+0

的人說,'__init __ py'是強制性的,以創建一個包沒有聽說過[隱。命名空間包](https://www.python.org/dev/peps/pep-0420/)呢;這就是爲什麼你當前的項目結構不會在'import stats.cars as c'上引發錯誤。 – user2357112

+0

@ user2357112我知道Python 3中的隱式名稱空間,但它仍然沒有照顧我所看到的錯誤。 – wigging

回答

4

把一個__init__.py文件中stats文件夾(如其他人所說的),並把這個在它:

from .cars import neon, mustang 
from .trucks import truck_a, truck_b 

不是很簡明,但更容易將使用*通配符:

from .cars import * 
from .trucks import * 

這樣,__init__.py腳本會爲您導入一些導入到自己的名稱空間。

現在你可以使用函數/類從neon/mustang模塊導入後直接stats

import stats as st 
st.mustang() 
+0

我試過'__init __。py'的方法,但是我仍然得到一個關於導入不被看到的錯誤。請看我更新的問題。 – wigging

+3

您需要指定一個相對導入:'from .cars import *'。 – chepner

+2

是的,這是Python 2式隱含的相對導入。你需要顯式的'.cars'相對導入。 – user2357112

0

在你的統計文件夾中添加空__init__.py文件,併發生魔法。

+0

我嘗試了'__init __。py'方法,仍然出現錯誤。 – wigging

0

您是否嘗試過類似 from cars import stats as c

您可能還需要一個空__init__.py文件在該目錄中。

host:~ lcerezo$ python 
Python 2.7.10 (default, Oct 23 2015, 18:05:06) 
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> from boto.s3.connection import S3Connection as mys3 
>>> 
+0

import stats.cars as c === from stats import cars as c –

0

您需要創建__init__.py文件夾的統計信息。

__init__.py文件需要使Python將目錄視爲包含包。 Documentation