gpt4 book ai didi

python - 对象在 python 的 protobuf 上没有属性 'add'

转载 作者:行者123 更新时间:2023-11-28 21:13:50 25 4
gpt4 key购买 nike

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

我的原型(prototype) 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 (most recent call last): File "ndemo.py", line 8, in base_request = contReq.baseRequest.add() AttributeError: 'BaseRequest' object has no attribute 'add'

最佳答案

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

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

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

关于python - 对象在 python 的 protobuf 上没有属性 'add',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32308853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com