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

使用pytest-mock mock类双下划线属性报错AttributeError如何解决?

问题原因

  • 该报错由Python的**名称改写(Name Mangling)**机制触发:所有以双下划线__开头、且末尾下划线数量不超过1的类属性,Python会自动将其重命名为_<类名>__<原属性名>的格式,目的是避免子类意外覆盖父类的私有属性。
  • 你在MyClass中定义的__attribute,实际在类的属性表中存储的名称是_MyClass__attribute,因此直接patch__attribute会提示属性不存在。

解决方法

方案1:使用mocker.patch.object

直接对改写后的属性名执行patch即可:

def test_1(mocker):
    with mocker.patch.object(MyClass, '_MyClass__attribute', {'something': 'new'}):
        test = MyClass()
        # 后续测试逻辑

方案2:使用字符串路径+PropertyMock

字符串路径中也替换为改写后的属性名:

def test_2(mocker):
    with mocker.patch('directory.my_class.MyClass._MyClass__attribute', new_callable=mocker.PropertyMock) as a:
        a.return_value = {'something': 'new'}
        test = MyClass()
        # 后续测试逻辑

直接赋值的修改方式

你之前尝试的直接赋值操作同理,替换为改写后的属性名即可生效:

MyClass._MyClass__attribute = {'something': 'new'}

补充说明

如果你没有强制需要双下划线私有属性的场景,建议改用单下划线_attribute作为属性名:这是Python约定俗成的私有属性标记,不会触发名称改写,patch时直接使用_attribute作为属性名即可,操作更简便。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 20:06:04