繁体   English   中英

Protobuf 在 Python 中按索引修改字段

[英]Protobuf modify field by index in Python

proto2

message Test {
  optional string fieldA = 1;
  optional string fieldB = 2;
}

在 Python2 中,如果我只有索引,如何修改字段?

例如,我想将索引为 1 的字段设置为“Value1”

在 C++ 中,相当于使用:

const FieldDescriptor *Descriptor::field(int index) const

https://developers.google.com/protocol-buffers/docs/reference/cpp/google.protobuf.descriptor#Descriptor.field.details

每个生成的 protobuf 消息类都有一个 DESCRIPTOR 字段: https : //developers.google.com/protocol-buffers/docs/pythontutorial

看一下描述符文档:

字段:(FieldDescriptors 列表)此类型中所有字段的字段描述符。

因此,要通过索引获取字段名称,请使用:

field_name = message.DESCRIPTOR.fields[index].name

然后,您可以使用 setattr 设置该值:

setattr(message, field_name, 'new_value')

(参见: 在 python 中使用 google protobuffers 反射

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM