【问题标题】:object has no attribute 'add' on python's protobuf对象在 python 的 protobuf 上没有属性“add”
【发布时间】:2015-08-31 10:10:56
【问题描述】:

我想在 python 上测试 protobuf 的 API 上的嵌套消息。

我的原型 ndemo.proto 文件是:

package ndemotest;

message BaseRequest
{
    required bytes Key = 1;
}

message ContRequest
{
    required BaseRequest baseRequest = 1;
    optional string Url = 2;
}

我的 python ndemo.py 代码是:

import binascii
import ndemo_pb2


contReq = ndemo_pb2.ContRequest()
contReq.Url="www.google.com"

base_request = contReq.baseRequest.add()
base_request.Key="12345"


packed_data = contReq.SerializeToString()

print 'sending "%s"' % binascii.hexlify(packed_data) 

当我以python ndemo.py 运行脚本时,出现错误

Traceback(最近一次调用最后一次):文件“ndemo.py”,第 8 行,在 base_request = contReq.baseRequest.add() AttributeError: 'BaseRequest' 对象没有属性 'add'

【问题讨论】:

    标签: python protocol-buffers


    【解决方案1】:

    repeated 字段只有 add(),这就是重点。

    在您的情况下,由于baseRequestrequired,您应该简单地将值直接分配给BaseRequest 中的字段,例如:

    contReq = ndemo_pb2.ContRequest()
    contReq.baseRequest.key = "12345"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-19
      • 2014-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-05
      • 2014-05-14
      相关资源
      最近更新 更多