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

Python初始化嵌套Protobuf消息报错:Room无Attributes字段

正确初始化嵌套Protobuf消息的解决方法

问题场景

你定义的Protobuf结构如下:

message House {
    message Room {
        message Attributes {
            string bed = 1;
            string desk = 2;
        }
    }
    message Kitchen {
        message Attributes {
            string stove = 1;
            string fridge = 2;
        }
    }
    Room room = 1;
    Kitchen kitchen = 2; 
 }

尝试用以下代码初始化时触发报错 ValueError: Protocol message Room has no "Attributes" field.:

attributes = House.Room.Attributes(
        bed = "Queen",
        desk = "Office desk"
    )

request = House(
        room=House.Room(
            Attributes = attributes
        ),
        sourceFactAttributes=None
    )

问题原因

你的Protobuf定义中,Room 和 Kitchen 仅嵌套了 Attributes 类型,但没有在消息内部声明对应类型的字段。生成的Python代码里,Room 类自然不存在名为 Attributes 的属性,因此初始化时抛出错误。同时你误用了类型名(大写的Attributes)而非字段名。

解决步骤

  1. 修改Protobuf定义,添加字段
    给Room和Kitchen分别添加对应Attributes类型的字段(字段名建议用小写,符合Protobuf命名规范):

    message House {
        message Room {
            message Attributes {
                string bed = 1;
                string desk = 2;
            }
            // 新增Attributes类型的字段
            Attributes attributes = 1;
        }
        message Kitchen {
            message Attributes {
                string stove = 1;
                string fridge = 2;
            }
            // 新增Attributes类型的字段
            Attributes attributes = 1;
        }
        Room room = 1;
        Kitchen kitchen = 2; 
     }
    

    修改完成后,重新用protoc命令生成Python代码。

  2. 正确初始化对象
    初始化时使用**小写的字段名attributes**匹配Protobuf定义,而非类型名:

    # 创建Room的Attributes实例
    room_attrs = House.Room.Attributes(
        bed="Queen",
        desk="Office desk"
    )
    
    # 初始化House对象
    request = House(
        room=House.Room(attributes=room_attrs),
        # 注意:如果sourceFactAttributes未在原Protobuf定义中声明,需删除该参数
        sourceFactAttributes=None
    )
    

补充说明

  • Protobuf中,嵌套消息仅定义类型,必须显式声明字段才能在父消息中使用该类型。
  • 生成的Python代码中,字段名对应Protobuf定义中的小写名称,类型名保留嵌套类的大写名称,注意区分二者。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 03:24:21