【问题标题】:Import functions directly from Python 3 modules直接从 Python 3 模块导入函数
【发布时间】:2015-12-18 03:26:37
【问题描述】:

对于 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是创建包的必要条件的人还没有听说过implicit namespace packages;这就是为什么您当前的项目结构不会在 import stats.cars as c 上引发错误的原因。
  • @user2357112 我知道 Python 3 中的隐式命名空间,但它仍然无法解决我看到的错误。

标签: python python-3.x python-import


【解决方案1】:

__init__.py 文件放在stats 文件夹中(正如其他人所说),并将其放入其中:

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

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

from .cars import *
from .trucks import *

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

现在您可以在导入 stats 后直接使用 neon/mustang 模块中的函数/类:

import stats as st
st.mustang()

【讨论】:

  • 我尝试了__init__.py 方法,但我仍然收到关于未看到导入的错误。请查看我更新的问题。
  • 需要指定相对导入:from .cars import *.
  • 是的,这是 Python 2 风格的隐式相对导入。您需要显式的 .cars 相对导入。
  • 好的,我需要 .cars 导入而不是 carsfrom stats.cars import * 也可以使用
【解决方案2】:

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

【讨论】:

  • 我尝试了__init__.py 方法,但仍然出现错误。
【解决方案3】:

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

__init__.py 文件是使 Python 将目录视为包含包所必需的。 Documentation

【讨论】:

    【解决方案4】:

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

    【讨论】:

    • import stats.cars as c === from stats import cars as c
    猜你喜欢
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    • 2011-10-09
    • 1970-01-01
    • 2015-03-05
    • 2021-02-05
    • 2014-10-04
    • 1970-01-01
    相关资源
    最近更新 更多