【问题标题】:Dynamically access oneof value from a protobuf从 protobuf 动态访问 oneof 值
【发布时间】:2018-07-19 11:22:22
【问题描述】:

假设我定义了这样的 protobuf 消息

message Config {
    oneof config{
         A a = 1;
         B b = 2;
    }
}

现在在 python 代码中,当我解析 Config 的消息实例时,我可以使用

获取字段名称之一
field = config.WhichOneof('config')

但是我应该如何使用我得到的字段名访问 A?我不想写这样的东西:

if field == 'a':
    return config.a
else
    return config.b

因为我只想用 a 或 b 获取下划线值,所以我已经知道它的类型。有更好的解决方案吗?谢谢!

【问题讨论】:

    标签: python protocol-buffers


    【解决方案1】:

    你可以使用getattr:

    data = getattr(config, config.WhichOneof('config')).value
    

    由于WhichOneof('config') 返回'a''b',只需使用getattr 动态访问属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多