如何清除Protocol Buffer字段?解决删除及赋值None报错问题
如何清除Protocol Buffer变量?
给定如下.proto文件:
message Product { optional float price = 5; }
若尝试执行删除操作:
del product.price
会出现如下错误:
AttributeError: can't delete attribute
若尝试将变量设为None:
product.price = None
则会出现如下错误:
TypeError: Cannot set mypackage.Product.price_was to None: None has type <class 'NoneType'>, but expected one of: numbers.Real
正确的清除方法
对于Protocol Buffer的可选字段,需使用对应的ClearField()方法清除单个字段值,示例代码如下:
product.ClearField("price")
如果需要一次性清除所有字段,可以使用Clear()方法:
product.Clear()
内容的提问来源于stack exchange,提问作者tread
相关产品推荐
相关产品推荐

