Python AttributeError:不允许分配给协议消息对象中的复合字段“任务”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18376190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:36:11  来源:igfitidea点击:

AttributeError: Assignment not allowed to composite field "task" in protocol message object

pythonprotocol-buffers

提问by gezhonglunta

I'm using protocol-buffers python lib to send data,but it's have some problems, so

我正在使用协议缓冲区 python lib 发送数据,但它有一些问题,所以

Traceback (most recent call last):
  File "test_message.py", line 17, in <module>
    ptask.task = task
  File "build\bdist.win32\egg\google\protobuf\internal\python_message.py", line
513, in setter
AttributeError: Assignment not allowed to composite field "_task" in protocol message object.

the src as follows:

src 如下:

proto file:

原型文件:

message task {
    required int32 id = 1;
    required string msg = 2;
}

message task_info {
    required task task = 1;
}

python code:

蟒蛇代码:

task = yacc.task()
task.id = 1000
task.msg = u"test"
ptask = yacc.task_info() 
ptask.task = task # this line happen the runtime error 

采纳答案by Martin Maillard

I don't know protocol-buffersbut I took a look at the docsand it says:

我不知道协议缓冲区,但我看了看文档,它说:

You cannot assign a value to an embedded message field. Instead, assigning a value to any field within the child message implies setting the message field in the parent.

您不能为嵌入的消息字段赋值。相反,为子消息中的任何字段赋值意味着在父消息中设置消息字段。

So I'm assuming this should work:

所以我假设这应该有效:

task = yacc.task()
task.id = 1000
task.msg = u"test"
ptask = yacc.task_info() 
ptask.task.id = task.id
ptask.task.msg = task.msg

回答by Aleksandro M Granda

I'm new to protocol-buffers too and faced with the same problem. I've found this methodhelpful.

我也是协议缓冲区的新手,面临同样的问题。我发现这个方法很有帮助。

I think it should work:

我认为它应该有效:

task = yacc.task()
task.id = 1000
task.msg = u"test"
ptask = yacc.task_info() 
ptask.task.MergeFrom(task)

回答by John McFarlane

Try CopyFrom:

尝试复制自

ptask.task.CopyFrom(task)