protobuf 的 HasField 函数期望什么参数



考虑以下结构

message Fly {
  uint32 dtime = 1;
}

但是HasField函数不起作用:

>>> d.ListFields()[0][0].name
'dtime'
>>> d.ListFields()[0][0].full_name
'Fly.dtime'
>>> 
>>> d.HasField('dtime')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/.../lib/python2.7/site-packages/google/protobuf/internal/python_message.py", line 825, in HasField
    raise ValueError(error_msg % field_name)
ValueError: Protocol message has no non-repeated submessage field "dtime"
>>> d.HasField('Fly.dtime')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/.../lib/python2.7/site-packages/google/protobuf/internal/python_message.py", line 825, in HasField
    raise ValueError(error_msg % field_name)
ValueError: Protocol message has no non-repeated submessage field "Fly.dtime"

HasField期望哪些参数?

我想你误解了HasField()做什么。它不检查 protobuf 类型是否通过名称定义特定字段。它的作用是检查给定消息字段的名称,是否为当前实例设置了该字段。

正如文档所指出的,在 proto3 中为非消息字段调用 HasField 将引发错误。

最新更新