Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 无法从其他文件导入函数_Python_Python 3.x - Fatal编程技术网

Python 无法从其他文件导入函数

Python 无法从其他文件导入函数,python,python-3.x,Python,Python 3.x,我有一个名为hotel\u helper.py的文件,我想从中导入一个名为demo1的函数,但我无法导入它 我的hotel\u 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'

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

我的
hotel\u 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'

当我使用
从hotel.helpers.hotel\u helper import*
而不是
从hotel.helpers.hotel\u helper import demo1导入时,它会工作并调用该函数。我尝试使用
从hotel.helpers导入hotel\u helper
导入整个文件,然后使用
hotel\u helper.demo1()
调用该函数,效果良好。我不明白第一种方法出了什么问题。我想直接导入函数,而不是使用
*
或导入整个文件。

这里有一个链接,您可以从中了解它:

从文件名导入函数

 from hotel.helpers import demo1


    demo1()

如果文件名为hotel_helper.py,则必须选择如何导入演示1:

您可以作为导入整个模块hotel_helper,然后调用func:

import hotel_helper as hh
hh.demo1()
您只能从模块导入函数demo1,如下所示:

from hote_helpers import demo1
demo1()

可以使用以下语句导入py文件:

#其他导入
导入操作系统
导入系统
如果“./hotel”不在sys.path中:
系统路径插入(0'/酒店')
从酒店进口*
注意:
对于类似于PyCharm的IDE,可以使用项目结构设置选项卡(CTRL+ALT+S)指定导入路径

有用的堆栈溢出问题[可能离题]:

使用PyCharm文档管理导入:

这可能是一个副本:

我从您发布的2个文件中创建了两个文件(defdemo.py和rundefdemo.py),并将代码中的“hotel.helpers.hotel\u helper”替换为“defdemo”。我的2个文件位于windows 10上Python 3.7的脚本目录中,我的脚本目录位于Python路径文件python37中。成功了


defdemo.py


def demo1(): 打印('\n\n正在尝试导入此函数')


rundefdemo.py


从defdemo导入demo1

演示1()


输出



尝试导入此函数时

我能够解决此问题,它与我在文件中进行的一些导入有关,当我删除我的
hotel\u helper.py
中的所有导入语句时,代码开始按预期工作,但我不理解问题发生的原因。不管怎样,它都能工作。

目录树是什么样子的(这些文件在哪里?),以及
\uuuu init\uuuuuuuuupy.py
文件中有什么?请具体说明您在谈论哪个init.py文件@kwinkunks@ShubhamDevgan要将python模块作为软件包使用,您需要在其中创建s
\uuu init\uu
文件。这就是@kwinkunksasking@beer44为什么它需要一个
\uuuuu init\uuuuu
,我只是导入了一个没有
\uuuuuu init\uuuuu
文件的函数,我不理解创建它的必要性,我对另一个文件也有同样的工作。@ShubhamDevgan,通过使用
\uuuu init\uuuuu.py
可以轻松导入模块,而不必知道模块的确切位置。因为python在其名称空间中包含了这一点。裁判
 from hotel.helpers import demo1


    demo1()