![](/img/trans.png)
[英]in protobuf python api how to add element to nested message repeated property?
[英]How to parse a nested protobuf message, python
我創建了以下 protobuf 對象:
message House {
message Room {
message Attributes {
string bed = 1;
string desk = 2;
}
}
message Kitchen {
message Attributes {
string stove = 1;
string fridge = 2;
}
}
Room room = 1;
Kitchen kitchen = 2;
}
我正在嘗試使用以下方法初始化 House 對象:
attributes = House.Room.Attributes(
bed = "Queen",
desk = "Office desk"
)
request = House(
room=House.Room(
Attributes = attributes
),
sourceFactAttributes=None
)
但是,我不斷收到以下錯誤: ValueError: Protocol message Room has no "Attributes" field.
像這樣嵌套消息會變得混亂。
您可能會發現保持一切平坦更容易,即在頂層將House
、 Room
、 Attributes
都定義為消息。 見最后的例子。
您的問題是消息(類型) Attributes
在消息House
中定義,但未作為字段引用。
這對應於您對Room
和Kitchen
所做的操作,在定義消息(類型)之后,您可以定義一個使用該類型的字段。
解決方案是將字段添加到消息Room
和消息Kitchen
中,類型為Attributes
,即:
message House {
message Room {
message Attributes {
string bed = 1;
string desk = 2;
}
Attributes attributes = 1; // Here
}
message Kitchen {
message Attributes {
string stove = 1;
string fridge = 2;
}
Attributes attributes = 1; // Here
}
Room room = 1;
Kitchen kitchen = 2;
}
我認為這更容易理解為:
message House {
Room room = 1;
Room kitchen = 2; // Room==Kitchen so define it once
}
message Room {
Attributes attributes = 1;
}
message Attributes {
string bed = 1;
string desk = 2;
}
注意扁平化消息也使消息定義和字段類型之間的區別更加清晰。 而且,在這種情況下,讓我們看到
Room
和Kitchen
是相同的定義,因此可以從共享類型中受益。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.