【问题标题】:AttributeError: Assignment not allowed to composite field "task" in protocol message objectAttributeError:不允许对协议消息对象中的复合字段“任务”进行分配
【发布时间】:2013-08-24 22:22:57
【问题描述】:

我正在使用protocol-buffers 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.

src如下:

原型文件:

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

message task_info {
    required task task = 1;
}

python 代码:

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

【问题讨论】:

    标签: python protocol-buffers


    【解决方案1】:

    试试CopyFrom:

    ptask.task.CopyFrom(task)
    

    【讨论】:

    • @Cu2S StackExchange 的黄金法则:始终至少阅读前 两个 答案!
    • 这就是答案。其他答案中提到的MergeFrom 有时也很有用。
    【解决方案2】:

    我不知道 protocol-buffers,但我查看了 the docs,它说:

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

    所以我假设这应该可行:

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

    【讨论】:

    【解决方案3】:

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

    我认为它应该有效:

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

    【讨论】:

    • CopyFrom() 在清除对象后调用 MergeFrom()
    猜你喜欢
    • 1970-01-01
    • 2016-04-25
    • 2014-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-19
    • 2014-09-28
    • 1970-01-01
    相关资源
    最近更新 更多