gpt4 book ai didi

Python - 未找到模块

转载 作者:IT老高 更新时间:2023-10-28 22:15:35 25 4
gpt4 key购买 nike

我是 Python 的初学者。在开始之前,这是我的 Python 文件夹结构

-project
----src
------model
--------order.py
------hello-world.py

src 下我有一个名为 model 的文件夹,其中有一个名为 order.py 的 Python 文件,其内容如下:

class SellOrder(object):
def __init__(self,genericName,brandName):
self.genericName = genericName
self.brandName = brandName

接下来我的 hello-world.py 位于 src 文件夹中,比 order.py 高一级:

import model.order.SellOrder

order = SellOrder("Test","Test")

print order.brandName

每当我运行 python hello-world.py 都会导致错误

Traceback (most recent call last):
File "hello-world.py", line 1, in <module>
import model.order.SellOrder
ImportError: No module named model.order.SellOrder

有什么我错过的吗?

最佳答案

Python 中的所有模块都必须具有特定的目录结构。 You can find details here.

model 目录下创建一个名为 __init__.py 的空文件,这样您的目录结构将如下所示:

.
└── project
└── src
├── hello-world.py
└── model
├── __init__.py
└── order.py

同样在您的 hello-world.py 文件中将导入语句更改为以下内容:

from model.order import SellOrder

应该可以解决的

P.S.:如果您将 model 目录放在其他位置(不在同一目录分支中),则必须使用 sys.path 修改 python 路径>.

关于Python - 未找到模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37233140/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com