2015-12-17 45 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