[英]Protobuf modify field by index in Python
proto2
message Test {
optional string fieldA = 1;
optional string fieldB = 2;
}
In Python2 how can I modify the field if I only have the index?在 Python2 中,如果我只有索引,如何修改字段?
Eg I'd like to set field with index 1 to "Value1"例如,我想将索引为 1 的字段设置为“Value1”
In C++ the equivalent would be to use:在 C++ 中,相当于使用:
const FieldDescriptor *Descriptor::field(int index) const
https://developers.google.com/protocol-buffers/docs/reference/cpp/google.protobuf.descriptor#Descriptor.field.details https://developers.google.com/protocol-buffers/docs/reference/cpp/google.protobuf.descriptor#Descriptor.field.details
Every generated protobuf message class has a DESCRIPTOR field: https://developers.google.com/protocol-buffers/docs/pythontutorial每个生成的 protobuf 消息类都有一个 DESCRIPTOR 字段: https : //developers.google.com/protocol-buffers/docs/pythontutorial
Take a look at Descriptor documentation:看一下描述符文档:
fields: (list of FieldDescriptors) Field descriptors for all fields in this type.字段:(FieldDescriptors 列表)此类型中所有字段的字段描述符。
Therefore, to get field name by index, use:因此,要通过索引获取字段名称,请使用:
field_name = message.DESCRIPTOR.fields[index].name
Then, you can set the value using setattr:然后,您可以使用 setattr 设置该值:
setattr(message, field_name, 'new_value')
(See: using google protobuffers reflection in python ) (参见: 在 python 中使用 google protobuffers 反射)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.