【问题标题】:Access fields value from a oneof object Python从一个对象 Python 访问字段值
【发布时间】:2020-09-04 02:06:45
【问题描述】:

让我们来看看这个 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-buffers grpc-python proto3


    【解决方案1】:

    通过Python Tutorial 了解示例和一般 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-30
      • 1970-01-01
      • 1970-01-01
      • 2020-01-04
      • 1970-01-01
      • 2016-09-26
      • 1970-01-01
      相关资源
      最近更新 更多