You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法从模块导入类: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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 07:35:22