直接从 Python 3 个模块导入函数

Import functions directly from Python 3 modules

我有一个 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'

我还尝试在 stats 文件夹中放置一个 __init__.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])

如何在 Python 3 中创建像 NumPy 这样的包来直接访问模块中的函数?

在您的统计文件夹中添加空的 __init__.py 文件,奇迹就会发生。

你试过类似的东西吗 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
>>>

您需要在 stats 文件夹中创建 __init__.py 文件。

需要 __init__.py 文件才能使 Python 将目录视为包含软件包。 Documentation

stats文件夹里放一个__init__.py文件(别人说的),把这个放进去:

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

不太简洁,但使用 * 通配符更容易:

from .cars import *
from .trucks import *

这样,__init__.py 脚本会为您做一些导入,导入到它自己的命名空间中。

现在您可以在导入 stats:

后直接从 neon/mustang 模块使用 functions/classes
import stats as st
st.mustang()