给定一个原型(prototype)定义
message EndpointResult {
int32 endpoint_id = 1;
// property id as key
map<int32, TimeSeries> properties = 2;
}
message TimeSeries {
repeated TimeEntry value = 2;
}
message TimeEntry {
int32 time_unit = 1;
float value = 2;
}
我希望在 EndpointResult 类中填充 map 。我尝试了 docs 中建议的不同方法但都对我提出了一个错误。
设置测试类
end_point_rslt = nom.EndpointResult()
end_point_rslt.endpoint_id=0
ts = nom.TimeSeries()
te = ts.value.add()
te.time_unit = 0
te.value = 5.
然后尝试不同的方法:
end_point_rslt.properties[0] = ts
ValueError: Direct assignment of submessage not allowed
end_point_rslt.properties[0].submessage_field = ts
AttributeError: Assignment not allowed (no field "submessage_field" in protocol message object).
end_point_rslt.properties.get_or_create(0)
end_point_rslt.properties[0] = ts
ValueError: Direct assignment of submessage not allowed
end_point_rslt.properties.get_or_create(0)
end_point_rslt.properties[0].submessage_field = ts
AttributeError: Assignment not allowed (no field "submessage_field" in protocol message object).
end_point_rslt.properties = {0 : ts}
AttributeError: Assignment not allowed to repeated field "properties" in protocol message object.
end_point_rslt.properties.get_or_create(0)
end_point_rslt.properties = {0 : ts}
TypeError: Can't set composite field
任何关于如何在 python 中使用 Protocol Buffer 映射的示例将不胜感激!
最佳答案
看了文档之后,我意识到问题出在我给字典分配了一个类。
正确的语法是
end_point_rslt = nom.EndpointResult()
end_point_rslt.endpoint_id=0
te = end_point_rslt.properties[0].value.add()
te.time_unit = 0
te.value = 5.
关于python - 如何在 Python 中使用 protobuf 映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53519472/