pycharm - 为什么导入无法在 Pycharm 中拉入类?
问题描述
我正在关注这个例子: https ://www.jetbrains.com/help/pycharm/pytest.html
我在 src/ 项目下创建了两个类: 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'
当我单独执行 Car.py 时,它运行正常。2个文件在同一个目录下,为什么导入失败?
解决方案
由于您使用的是 Python 3,因此您需要相对导入。将您的导入语句更改为以下内容:
from .Car import Car
推荐阅读
- javascript - 如何刷新绑定?
- selenium-chromedriver - WCT 无法在 Redhat Linux 中检测到 google chrome 浏览器
- javascript - 如何将从 postgres 数据库中选择的数据转换为 json 或 csv 以将其与 d3js lib 一起使用?
- gradle - 使用 gradle 合并 jar 以进行拆分包
- android - 从 Play 商店下载 apk 后,Google 地图无法在 Android 中运行
- android - 将图像沿某些表单数据 Retrofit 发布到 WCF Rest
- primeng - PrimeNg Steps 组件编号
- python - Python脚本使字符串与放置的字符的每个组合
- jsf - 在生产模式下禁用相位监听器
- php - 未找到 PHP Symfony curl 发布数据