protocol-buffers - 从一个对象 Python 访问字段值
问题描述
让我们看看这个 proto3 代码:
message Animal{
oneof animal_oneof {
CAT cat = 1;
DOG dog = 2;
}
}
message CAT{
int32 meow = 1;
int32 meow_2 = 2;
}
message DOG{
int32 woof = 1;
int32 woof_2 = 2;
int32 woof_3= 3;
int32 woof_4= 4;
}
我想从CAT
或访问字段DOG
。
我可以将oneof
值选择为:
selected_animal = request.Animal.WhichOneof("animal_oneof ")
但是我怎样才能动态访问每个字段呢?我必须getWoof()
为每个领域打电话吗?
我可以访问每个字段名称,例如:
for descriptor in request.Animal.DOG.DESCRIPTOR.fields_by_name
解决方案
浏览Python 教程以获取示例和一般 API 用法。
这是您给定的 ProtoBuf 定义 ( ) 的示例animal.proto
:
import animal_pb2
# serialization
a1 = animal_pb2.Animal()
a1.cat.meow = 1234;
a1.cat.meow_2 = 5678;
serialized = a1.SerializeToString()
# deserialization
a2 = animal_pb2.Animal()
a2.ParseFromString( serialized )
print( a2.cat )
输出:
meow: 1234
meow_2: 5678
推荐阅读
- c# - 使用 XSLT 从 XML 中查询和提取数据
- amazon-web-services - AWS:对 Metric Math 替代方案的担忧
- google-cloud-platform - 如何使用 Cloud Functions 在 Google Cloud Storage 的文件夹中下载文件?
- android - 设置可见性后如何修复LinearLayout项目的位置?
- javascript - 将 CSV 文件读取到 HTML 下拉菜单
- git - 如何配置 Araxis Merge 以与 Visual Studio Git 一起使用?
- apache-spark - 在 pyspark 中,是否可以用另一列填充?
- cordova - Inappbrowser Skype 通话
- c++ - What is the type of decltype(*int_iterator + 0)?
- asp.net - ASP.NET Core 等待 WebSocket.ReceiveAsync 阻止 IIS 关闭 dotnet.exe