python - 无法从另一个文件导入函数

标签 python python-3.x

我有一个名为 hotel_helper.py 的文件,我想从中导入一个名为 demo1 的函数,但我无法导入它。

我的hotel_helper.py文件:

def demo1():
    print('\n\n trying to import this function ')

我的其他文件:

from hotel.helpers.hotel_helper import demo1

demo1()

但我得到:

ImportError: cannot import name 'demo1' from 'hotel.helpers.hotel_helper'

当我使用 from hotel.helpers.hotel_helper import * 而不是 from hotel.helpers.hotel_helper import demo1 导入时,它可以工作并且该函数被调用。我尝试使用 from hotel.helpers import hotel_helper 导入整个文件,然后使用 hotel_helper.demo1() 调用该函数,效果很好。我不明白第一种方法有什么问题。我想直接导入函数,而不是使用 * 或导入整个文件。

最佳答案

如果您的文件名是 hotel_helper.py,您必须选择如何导入 demo1:

您可以将整个模块 hotel_helper 导入为,然后调用您的函数:

import hotel_helper as hh
hh.demo1()

您只能从模块中导入函数 demo1:

from hote_helpers import demo1
demo1()

关于python - 无法从另一个文件导入函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58117373/

相关文章:

python - Pelican、文章和页面导致 404 状态代码

python - 如何从两个列表中查找匹配的部分项目

python - Pip 不适用于 Ubuntu 上的 Python 3.10

python - 是否可以将 class.__init__() 的所有输入都作为一行中的属性?

python-3.x - GroupBy 但仍保留所有行

python - 如何通过开放的 shell 端口使用 python 套接字访问 Metasploitable 2 VM shell?

python - 如何将一个数字除以索引中的一个数字?

python - 语法错误: “],” invalid syntax - Dash Graph Building

Python Matplotlib : Clear figure when figure window is not open

python - 如何根据列名的前三个字符更改列名