问题记录:
最近在使用python对protobuf进行处理的时候,出现了一个问题,对repeated字段的值进行赋值时,使用add()函数会出现下面的报错。
及对LaneBuoudaryType中的types 进行赋值时使用了如下代码:
lane_boundary_type = LaneBoundaryType()
lane_boundary_type_types = lane_boundary_type.types.add()
报错:
AttributeError: 'google.protobuf.pyext._message.RepeatedScalarConta' object has no attribute 'add'
问题解释:
对于repeated的字段,如果该字段是一个子结构,可以使用add()函数,如下面代码中的LaneBoundary中的boundary_type字段
但是如果该repeated字段是一个基础数据类型,比如下面代码中的LaneBoundaryType中的types字段,就不能使用add(),可以直接使用append()函数进行赋值;
修改后的代码如下:
lane_boundary_type = LaneBoundaryType()
lane_boundary_type.types.append(4)
message LaneBoundaryType {
enum Type {
UNKNOWN = 0;
DOTTED_YELLOW = 1;
DOTTED_WHITE = 2;
SOLID_YELLOW = 3;
SOLID_WHITE = 4;
DOUBLE_YELLOW = 5;
CURB = 6;
};
// Offset relative to the starting point of boundary
optional double s = 1;
// support multiple types
repeated Type types = 2;
}
message LaneBoundary {
optional Curve curve = 1;
optional double length = 2;
// indicate whether the lane boundary exists in real world
optional bool virtual = 3;
// in ascending order of s
repeated LaneBoundaryType boundary_type = 4;
}