You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何清除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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 04:50:28