直接从Python 3模块导入函数
对于Python 3项目,我有以下文件夹结构,其中直接从Python 3模块导入函数,python,python-3.x,python-import,Python,Python 3.x,Python Import,对于Python 3项目,我有以下文件夹结构,其中vehicle.py是主脚本,文件夹stats被视为包含几个模块的包: cars模块定义以下功能: def neon(): print('Neon') print('mpg = 32') def mustang(): print('Mustang') print('mpg = 27') 使用Python 3,我可以从vehicle.py中访问每个模块中的函数,如下所示: import stats.cars
vehicle.py
是主脚本,文件夹stats
被视为包含几个模块的包:
cars
模块定义以下功能:
def neon():
print('Neon')
print('mpg = 32')
def mustang():
print('Mustang')
print('mpg = 27')
使用Python 3,我可以从vehicle.py
中访问每个模块中的函数,如下所示:
import stats.cars as c
c.mustang()
但是,我希望直接访问每个模块中定义的函数,但执行此操作时收到错误:
import stats as st
st.mustang()
# AttributeError: 'module' object has no attribute 'mustang'
我还尝试在stats
文件夹中放置一个\uuuu init\uuuu.py
文件,其中包含以下代码:
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])
如何在Python3中创建一个像NumPy这样的包来直接访问模块中的函数?在stats文件夹中添加空的
\uu init\uuuupy.py
文件,就会发生神奇的事情。您尝试过类似的方法吗
from cars导入统计数据为c
您可能还需要该目录中的一个空的\uuuuu init\uuuuu.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
>>>
您需要在stats文件夹中创建\uuuu init\uuuuu.py文件 \uuuu init\uuuuu.py文件是Python将目录视为包含包所必需的。
将
\uuuu init\uuuu.py
文件放入stats
文件夹(正如其他人所说),并将其放入其中:
from .cars import neon, mustang
from .trucks import truck_a, truck_b
不是很整洁,但是使用*
通配符更容易:
from .cars import *
from .trucks import *
通过这种方式,\uuuuu init\uuuuuu.py
脚本为您执行一些导入操作,将其导入到自己的命名空间中
现在,您可以在导入stats
后直接使用neon
/mustang
模块中的函数/类:
import stats as st
st.mustang()
导入stats.cars作为c==从stats导入cars作为cI尝试了
\uuu init\uuuuuuuuuuupy
方法,但仍然得到错误。说\uuu init\uuuuuuuupy
的人必须创建一个包,但还没有听说过;这就是为什么您当前的项目结构没有在导入stats.cars as c@user2357112时引发错误的原因。我知道Python 3中存在隐式名称空间,但它仍然没有考虑我看到的错误。我尝试了\uu init\uuuuuuuuuuy.py
方法,但仍然得到一个关于导入未被看到的错误。请查看我更新的问题。您需要指定一个相对导入:from.cars import*
。是的,这是Python 2风格的隐式相对导入。您需要显式的.cars
相对导入。好的,我需要的是.cars
导入,而不仅仅是cars
,stats.cars导入的也可以工作