对于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 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这样的包来直接访问模块中的函数?
将__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()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句