首页 > 解决方案 > 从一个对象 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

标签: protocol-buffersgrpc-pythonproto3

解决方案


浏览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

推荐阅读