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

跨目录运行Python单元测试报AttributeError的语法修正方法

问题根因

触发AttributeError: module 'an_example' has no attribute 'someMethod'报错的核心原因有两个:

  • 调用层级错误:你通过import an_example导入的是an_example.py对应的模块对象,但someMethod是定义在模块内部an_example类下的方法,不属于模块的直接属性,直接调用an_example.someMethod()自然找不到对应方法。
  • 类方法定义不符合Python语法规范:普通类实例方法的第一个参数必须是代表类实例本身的self,你当前的方法定义缺少这个必填参数,就算调整调用层级后也会触发参数不匹配的错误。
具体修正方案

1. 修正被测文件 C:\completely\different\path\an_example.py

给实例方法补上self参数,修正后代码如下:

class an_example:
    def __init__(self):  
        pass

    # 实例方法第一个参数固定为self,代表类实例本身
    def someMethod(self, firstString, secondString):
        print("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^")
        print("firstString is: ", firstString)
        print("secondString is: ", secondString)
        combinedString = firstString + secondString
        print("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^")
        return combinedString == "hello there"

补充:如果你希望不需要实例化类就能直接调用方法,可以给方法加@staticmethod装饰器标记为静态方法,这种写法不需要写self参数:

class an_example:
    def __init__(self):  
        pass

    @staticmethod
    def someMethod(firstString, secondString):
        print("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^")
        print("firstString is: ", firstString)
        print("secondString is: ", secondString)
        combinedString = firstString + secondString
        print("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^")
        return combinedString == "hello there"

2. 修正测试文件的调用逻辑

建议把路径导入逻辑放到文件顶部(不要塞在测试用例内部),同时调整方法调用的层级:

  • 如果用普通实例方法写法,需要先实例化类再调用方法,测试文件代码如下:
import unittest
import sys
# 提前把被测文件所在目录加入系统路径
sys.path.insert(0, 'C:\\completely\\different\\path\\')
import an_example

# 运行测试命令:python -m unittest test_an_example.py
class TestCommandBuilder(unittest.TestCase):
    def test_someMethod(self):
        firstString = "hello"
        secondString = ' there'
        # 先实例化类,再调用实例方法
        example_obj = an_example.an_example()
        returnBool = example_obj.someMethod(firstString, secondString)
        self.assertTrue(returnBool)

if __name__ == '__main__':
    unittest.main()
  • 如果用静态方法写法,不需要实例化,直接通过类名调用即可,把测试用例里的调用部分改成:
returnBool = an_example.an_example.someMethod(firstString, secondString)

规范提示:Python命名惯例中类名建议使用大驼峰格式(比如AnExample),你当前模块名和类名完全同名,很容易出现调用层级混淆的问题,建议调整命名减少同类错误。

内容的提问来源于stack exchange,提问作者CodeMed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 17:24:20