获取原始消息列表

Get list of proto messages

我是 protobufs 的新手,我似乎无法理解。 我有一个这样的原型文件。

message Address{
       string Home=1;
       State state=2;
       string Name=3;
enum State{
      STATE_UNKNOWN=0;
      STATE_ARCHIVED=1;
}
}

并且我已将数据添加到消息中,如下所示。

Address{
Home:"Cornfield";
State: STATE_UNKNOWN;
Name:"Corner";
}
Address{
Home:"Ham";
State: STATE_UNKNOWN;
Name:"Hammer";
}

数据=Address.getfielddescriptor() 字段描述符方法不能 return 像这样的值列表 数据=['Cornfield','Ham']

我该怎么做?

为了能够使用列表,您需要将字段定义为重复。因此,您需要在某个地方定义诸如地址簿之类的东西,您可以在其中存储所有地址:

message Address {
  string home = 1;
  State state = 2;
  string name = 3;
 
  enum State {
    STATE_UNKNOWN  = 0;
    STATE_ARCHIVED = 1;
  }
}

// Your address book message
message AddressBook {
  repeated addresses= 1;
}

接下来在 python 中使用如下:

address_book = AddressBook()
addr = address_book.addresses.add() 
addr.home = "Cornfield"
addr.state = STATE_UNKNOWN
addr.name = "Corner"

# You can also first create an address object and extend the list
addr2 = Address()
addr2.home = "Ham"
addr2.state = STATE_UNKNOWN
addr2.name = "Hammer"
address_book.addresses.extend(addr2)

# You can use the list of addresses like any other list:
# By index: address_book.addresses[0]
# or in a list: for addr in address_book.addresses:

其他扩展通讯录的方法可以参考protobuf文档here