簡體   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