簡體   English   中英

如何將實例對象分配給 protobuf 消息屬性

[英]How to assign an instance object to protobuf message attribute

使用test.photo文件:

syntax = "proto3";

message Phone {
  string number = 1;
}
message User {
  Phone phone = 1;
}

用它編譯:

python -m grpc_tools.protoc -I. --python_out=. test.proto

跑步:

    import test_pb2
    user = test_pb2.User()
    phone = test_pb2.Phone(number = '(123) 456 7890')
    user.phone = phone

引發AttributeError異常:

    Assignment not allowed to field "phone" in protocol message object.

有沒有辦法將phone對象分配給user.phone屬性?

如錯誤所述,protobuf 消息不支持分配。 有一個內置方法CopyFrom ,它使用給定消息的值/屬性覆蓋消息。

以下將使用phone的屬性填充user.phone的屬性:

import test_pb2

user = test_pb2.User()
phone = test_pb2.Phone(number = '(123) 456 7890')
user.phone.CopyFrom(phone)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM