下面是proto描述文件的定义
message Person { required string name = 1; required int32 id = 2; optional string email = 3; enum PhoneType { MOBILE = 0; HOME = 1; WORK = 2; } message PhoneNumber { required string number = 1; optional PhoneType type = 2 [default = HOME]; } repeated PhoneNumber phone = 4; } message AddressBook { repeated Person person = 1; }
在python中利用google.protobuf序列化数据进行通讯的时候,一定会遇到repeated的数据如何去创建
在这里我给大家分享一下:
import addressbook_pb2 person = addressbook_pb2.Person() person.id = 1234 person.name = "John Doe" person.email = "jdoe@example.com" phone = person.phone.add() phone.number = "555-4321" phone.type = addressbook_pb2.Person.HOME person.no_such_field = 1 person.id = "1234"
请注意加红的一行代码,这就是重点,如果想再添加一个的话phone2 = person.phone.add()即可,然后给phone2赋值。