为什么导入未能在Pycharm中拉入类?

为什么导入未能在Pycharm中拉入类?,pycharm,Pycharm,我举这个例子: 我在src/project下创建了两个类:Car.py和test_Car_pytest.py: class Car(object): def __init__(self, speed=0): self.speed = speed self.odometer = 0 self.time = 0 ... 然后在test_car_pytest.py中: from Car import Car def test_car_

我举这个例子:

我在src/project下创建了两个类:Car.py和test_Car_pytest.py:

class Car(object):
    def __init__(self, speed=0):
        self.speed = speed
        self.odometer = 0
        self.time = 0
   ...
然后在test_car_pytest.py中:

from Car import Car

def test_car_brake():
    car = Car(50)
    assert car.speed == 45
在PyCharm中,import语句显示“Car”是一个未解析的引用。当我尝试运行它时,出现以下错误:

============================= test session starts ==============================
platform darwin -- Python 3.6.8, pytest-4.2.0, py-1.7.0, pluggy-0.8.1
rootdir: /Users/minn/PycharmProjects/test/src, inifile:
test_car_pytest.py:None (test_car_pytest.py)
ImportError while importing test module '/Users/minn/PycharmProjects/test/src/test_car_pytest.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
test_car_pytest.py:1: in <module>
    from Car import Car
E   ModuleNotFoundError: No module named 'Car'
=================================================测试会话开始==============================
平台darwin——Python 3.6.8、pytest-4.2.0、py-1.7.0、Plugy-0.8.1
rootdir:/Users/minn/PycharmProjects/test/src,文件:
test\u car\u pytest.py:无(test\u car\u pytest.py)
导入测试模块“/Users/minn/PycharmProjects/test/src/test_car_pytest.py”时导入错误。
提示:确保您的测试模块/包具有有效的Python名称。
回溯:
测试车测试。py:1:in
从汽车进口汽车
E ModuleNotFoundError:没有名为“Car”的模块

当我单独执行Car.py时,它会正常运行。这两个文件位于同一目录下,为什么导入失败?

因为您使用的是Python 3,所以需要相对导入。将导入语句更改为以下内容:

from .Car import Car