无法从模块导入类:pytest测试子类时的导入报错求助
解决pytest导入Candy类失败的问题
问题根源
你遇到的“无法从‘candy’导入‘Candy’”错误,本质是Python模块导入路径配置错误,加上项目未按规范包结构组织导致的。
步骤1:规范项目目录结构
确保DessertShop是合法Python包,必须添加__init__.py文件(可空),最终结构如下:
DessertShop/ ├── __init__.py ├── dessert_item.py ├── candy.py └── test_candy.py
步骤2:修正模块内的导入语句
修正dessert_item.py
保持原代码即可,无需额外导入:
class DessertItem: def __init__(self, name): self.name = name
修正candy.py
使用相对导入引用同包内的DessertItem:
from .dessert_item import DessertItem class Candy(DessertItem): def __init__(self, name, candy_weight, price_per_pound): super().__init__(name) self.candy_weight = candy_weight self.price_per_pound = price_per_pound
修正test_candy.py
同样用相对导入引用Candy类:
from .candy import Candy def test_candy_constructor(): candy = Candy("Chocolate Candy", 0.5, 10.99) assert candy.name == "Chocolate Candy" assert candy.candy_weight == 0.5 assert candy.price_per_pound == 10.99 def test_candy_attributes(): candy = Candy("Chocolate Candy", 0.5, 10.99) candy.candy_weight = 0.75 assert candy.candy_weight == 0.75 def test_candy_methods(): candy = Candy("Chocolate Candy", 0.5, 10.99) # 补充你需要测试的方法逻辑,比如计算总价
步骤3:正确运行pytest
必须在DessertShop的父目录下执行pytest命令,不能直接在DessertShop目录内运行。比如:
- 假设
DessertShop位于当前工作目录下,运行:
pytest DessertShop/test_candy.py -v
- 或者让pytest自动发现所有测试文件:
pytest -v
额外注意事项
- 不要直接在
DessertShop目录下运行python test_candy.py,这种方式会破坏包的导入逻辑 - 如果项目需要被外部模块引用,可将
DessertShop的父目录添加到PYTHONPATH环境变量中
内容的提问来源于stack exchange,提问作者Hayden Poyfair
相关产品推荐
相关产品推荐

