英文:
When constructing an instance of a Python protobuf message, I keep getting positional argument error
问题
我正在使用pb_2,并想构建消息的实例,但一直遇到位置参数错误。我可以从所有其他消息中构建实例,但当涉及到以下示例时,我卡住了。
我有以下三条消息:
message Foo {
int32 num = 1;
repeated KeyValuePair features = 2;
}
message KeyValuePair {
string key = 1;
Value value = 2;
}
message Value {
oneof oneOfValue {
string strValue = 1;
int64 intValue = 2;
}
}
我想构建一个类似于以下的Foo实例:
foo {
num: 123
features: [KeyValuePair {key: 'key1', value: 'value1'},
KeyValuePair {key: 'key2', value: 'value2'}]
}
我尝试了以下方法,但一直收到位置参数错误('不允许位置参数'):
my_foo = Foo(num=123,
features=[KeyValuePair(key='key1', value='value1'),
KeyValuePair(key='key2', value='value2')])
我没有使用任何位置参数。有人能帮忙吗?
谢谢!
英文:
I'm using pb_2 and want to consturct instances of a message but keep facing positional argument error. I can construct instances from all other messages but when it comes to the following example, I get stcuk.
I have the following three messages:
message Foo {
int32 num = 1;
repeated KeyValuePair features = 2;
}
message KeyValuePair {
string key = 1;
Value value = 2;
}
message Value {
oneof oneOfValue {
string strValue = 1;
int64 intValue = 2;
}
}
I want to construct an instance of Foo that looks like this:
foo {
num: 123
features: [KeyValuePair {key: 'key1', value: 'value1'},
KeyValuePair {key: 'key2', value: 'value2'}]
}
I tried the following and keep getting positional argument error ('no positional arguments allowed'):
my_foo = Foo(num=123,
features=[KeyValuePair(key='key1', value='value1'),
KeyValuePair(key='key2', value='value2')])
I am not using any positional arguments. Can anyone help?
Thanks!
答案1
得分: 1
你似乎错误地实例化了 Foo
,请注意我对 Protocol Buffers 不太熟悉... 你已经声明了 KeyValuePair
如下:
message KeyValuePair {
string key = 1;
Value value = 2;
}
这意味着它将一个字符串值映射到一个 Value
实例。所以你需要这样做:
my_foo = Foo(
num=123,
features=[
KeyValuePair(key="key1", value=Value(strValue="value1")),
KeyValuePair(key="key2", value=Value(strValue="value2")),
],
)
在我的系统上,使用你的示例 .proto
文件(在顶部添加 syntax = "proto3";
),这将不会产生错误。
英文:
With the caveat that I am not familiar with protobuf...aren't you instantiating Foo
incorrectly? You've declared that a KeyValuePair
looks like:
message KeyValuePair {
string key = 1;
Value value = 2;
}
So it maps a string value to a Value
instance. That means you would need:
my_foo = Foo(
num=123,
features=[
KeyValuePair(key="key1", value=Value(strValue="value1")),
KeyValuePair(key="key2", value=Value(strValue="value2")),
],
)
On my system, using your example .proto
file (adding syntax = "proto3";
at the top), that runs without errors.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论