如何将类导入其他文件?

问题描述 投票:0回答:1

我有这样的文件结构:

/app/sense/abstract/__init__.py
/app/sense/abstract/sensor.py
/app/sense/__init__.py
/app/sense/gps.py
/app/components.py
/app/main.py
/tests/unit/__init__.py
/tests/unit/context.py
/tests/unit/test_sense.py

sensor.py
定义了一个抽象基类 Sensor ,
gps.py
使用它来塑造 GPS 类。

components.py
的目的是促进 在一行中导入子文件夹中的所有类。到目前为止唯一的代码行是:

from .sense.gps import GPS

context.py
的目的是允许我导入类进行单元测试。它目前有以下几行代码:

from pathlib import Path
import sys

path = Path(__file__).resolve().parent.parent.parent
sys.path.insert(0, path)

import app.components as avc

最后,

test_sense.py
类包含用于测试
GPS
是否实现
Sensor
.

的代码

我遇到的问题是:每当我尝试运行

test_sense.py
文件时,我都会得到
ModuleNotFoundError
,说“应用程序”不存在。我怎样才能解决这个问题?

python python-3.x python-import
1个回答
1
投票

报错是因为运行test_sense.py文件时,'app'包不在Python路径中。解决此问题的一种方法是将“app”包添加到 test_sense.py 文件中的 Python 路径,类似于在 context.py 文件中所做的。以下是如何修改 test_sense.py 文件以将“app”包添加到 Python 路径:

import sys
from pathlib import Path

# Add the parent directory of the 'tests' directory to the Python path
sys.path.append(str(Path(__file__).resolve().parents[2]))

# Import the GPS class from the 'app' package
from app.sense.gps import GPS

# Import the Sensor class from the 'app' package
from app.sense.abstract.sensor import Sensor

# Define the test class
class TestGPS:

    # Test that GPS implements Sensor
    def test_implements_sensor(self):
        assert issubclass(GPS, Sensor)

此代码将“tests”目录的父目录添加到 Python 路径,这应该允许 Python 找到“app”包。然后,它从“app”包中导入 GPS 和传感器类,并像以前一样定义测试类。

© www.soinside.com 2019 - 2024. All rights reserved.