Python 从protobuf动态访问一个值
假设我定义了这样一个protobuf消息Python 从protobuf动态访问一个值,python,protocol-buffers,Python,Protocol Buffers,假设我定义了这样一个protobuf消息 message Config { oneof config{ A a = 1; B b = 2; } } 现在在python代码中,当我解析Config的消息实例时,我可以使用 field = config.WhichOneof('config') 但是我应该如何使用我得到的字段名访问?我不想写这样的东西: if field == 'a': return config.a else
message Config {
oneof config{
A a = 1;
B b = 2;
}
}
现在在python代码中,当我解析Config的消息实例时,我可以使用
field = config.WhichOneof('config')
但是我应该如何使用我得到的字段名访问?我不想写这样的东西:
if field == 'a':
return config.a
else
return config.b
因为我只想得到a或b的下划线值,我已经知道它的类型了。有更好的解决办法吗?谢谢 您可以使用
getattr
:
data = getattr(config, config.WhichOneof('config')).value
由于whichonof('config')
返回'a'
或'b'
,只需使用getattr
动态访问该属性即可