Python OOP TypeError求助:float()参数为NoneType问题
解决CSV读取时float()/int()参数为NoneType的错误
错误原因
你遇到的TypeError: float() argument must be a string or a real number, not 'NoneType',本质是item.get('price')或item.get('quantity')返回了None。这通常由两个原因导致:
- CSV文件的表头和代码中使用的字段名不匹配(比如表头是
Price而不是price,或字段名带有空格) - CSV某行数据缺失
price或quantity字段的值
另外注意到你的类方法名拼写错误:intantiate_from_csv应该是instantiate_from_csv(少了一个s),虽当前调用未报错,但属于不规范写法。
解决方案
1. 检查并修正CSV文件
确保items.csv的表头是准确的小写字段名,第一行格式如下:
name,price,quantity Apple,10.5,3 Banana,5.2,5
同时检查所有行数据,确保没有缺失price或quantity的值。
2. 增加数据校验逻辑
在创建Item对象前,先校验字段是否存在且不为空,避免转换None值报错:
@classmethod def instantiate_from_csv(cls): with open('items.csv', 'r') as f: reader = csv.DictReader(f) items = list(reader) for item in items: # 检查必要字段是否存在 if not all(key in item for key in ['name', 'price', 'quantity']): print(f"跳过无效行:{item}") continue # 检查字段值是否为空字符串 if not item['price'].strip() or not item['quantity'].strip(): print(f"跳过值为空的行:{item}") continue # 创建Item对象(用cls替代Item更符合类方法规范) cls( name=item['name'], price=float(item['price']), quantity=int(item['quantity']), )
3. 可选:设置默认值
如果允许缺失字段使用默认值,可以用get()方法的第二个参数指定默认值:
cls( name=item.get('name', 'Unknown'), price=float(item.get('price', 0.0)), quantity=int(item.get('quantity', 0)), )
修正后的完整代码
import csv class Item: pay_rate = 0.8 all = [] def __init__(self, name: str, price: float , quantity: int): # 验证输入参数 assert quantity >= 0, f"数量 {quantity} 必须大于或等于0" assert price >= 0, "价格必须大于或等于0" # 赋值给实例 self.name = name self.price = price self.quantity = quantity # 添加到all列表 Item.all.append(self) def calculate_total_price(self): return self.price * self.quantity def apply_discount(self): self.price = self.price * self.pay_rate @classmethod def instantiate_from_csv(cls): with open('items.csv', 'r') as f: reader = csv.DictReader(f) items = list(reader) for item in items: if not all(key in item for key in ['name', 'price', 'quantity']): print(f"跳过无效行:{item}") continue if not item['price'].strip() or not item['quantity'].strip(): print(f"跳过值为空的行:{item}") continue cls( name=item['name'], price=float(item['price']), quantity=int(item['quantity']), ) def __repr__(self): return f"Item('{self.name}', {self.price}, {self.quantity})" Item.instantiate_from_csv() print(Item.all)
内容的提问来源于stack exchange,提问作者Hierat Seven
相关产品推荐
相关产品推荐

