简体   繁体   English

如何为协议缓冲区Python中的嵌入消息字段赋值

[英]How to assign a value to an embedded message field in Protocol buffer Python

I have following proto and I am trying to assign a value to an embedded message field 我有跟随proto,我正在尝试为嵌入的消息字段分配值

message Foo {
  required Bar bar = 1;
}
message Bar {
  optional int32 i = 1;
} 

When I am writing following code in python, It gives below error 当我在python中编写下面的代码时,它给出了以下错误

foo = Foo()
foo.bar.i = 1

Error: 错误:

AttributeError: 'instancemethod' object has no attribute 'i' AttributeError:'instancemethod'对象没有属性'i'

How to deal with this error? 如何处理这个错误?

To do what you want, in Python, you have to define the bar method within the Foo class. 要做到你想要的,在Python中,你必须在Foo类中定义bar方法。 Something like this will do it: 像这样的东西会这样做:

class Foo:
    i = 1

    def bar(self):
        return self.i

if __name__ == '__main__':
    foo = Foo()
    foo.bar = 1
    print(foo.bar)  # this will print 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python和协议缓冲区:如何从重复的消息字段中删除元素 - Python and protocol buffer: how to removed an element from a repeated message field Python 中的协议缓冲区:如何为嵌套元素设置值 - Protocol buffer in Python: How to set value to the nested element 将协议缓冲区编码的消息从 Python 服务器发送到 Java 客户端 - Sending Protocol Buffer encoded message from Python Server to Java Client python gevent websocket客户端收到回显协议缓冲区消息的错误“ DecodeError:截断的消息” - python gevent websocket client getting error “DecodeError: Truncated message” for echoed back protocol buffer message 如何为 protobuf 中的可选消息字段赋值? - How to assign values to an optional message field in protobuf? Google DLP:“ ValueError:协议消息值没有“ stringValue”字段。” - Google DLP: “ValueError: Protocol message Value has no ”stringValue“ field.” 在 Python 中读取协议缓冲区文件 - Reading a protocol buffer file in Python 如何使用谷歌协议缓冲区的python-trio? - How to use python-trio with google protocol buffer? 如何为 python 函数中的所有协议缓冲区对象添加类型提示? - How to add type hint for all protocol buffer objects in python functions? 如何从另一个Python包中导入协议缓冲区定义? - How to import protocol buffer definitions from another Python package?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM