[英]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.