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

Python新手求助:如何解决'int()参数不能为NoneType'错误?

解决int()参数为NoneType的报错问题

你遇到的int() argument must be a string, a bytes-like object or a real number, not 'NoneType'报错,核心原因是CSV文件的表头字段名带空格,导致代码里用item.get('price')、item.get('quantity')拿不到对应值,返回了None,而int()无法接收None作为参数。

解决步骤:

  1. 修正CSV文件格式
    把CSV的表头和数据行里逗号后的空格去掉,确保字段名和代码里引用的完全一致。修改后的CSV内容:

    name,price,quantity
    "Phone",100,1
    "Laptop",1000,3
    "Cable",10,5
    "Mouse",50,5
    "Keyboard",75,5
    
  2. 可选:给代码增加容错处理(避免后续类似问题)
    在转换数值时,先设置默认值,就算某个字段缺失也不会直接崩溃,比如:

    price=int(item.get('price', 0)),
    quantity=int(item.get('quantity', 0)),
    

修改后的完整代码:

import csv

class Item:
    pay_rate = 0.8  # 20%折扣后的支付率
    all = []
    def __init__(self, name: str, price: float, quantity = 0):
        # 参数合法性校验
        assert price >= 0, f"价格{price}不能小于0!"
        assert quantity >= 0, f"数量{quantity}不能小于0!"
        
        # 赋值给实例属性
        self.name = name
        self.price = price
        self.quantity = quantity
        
        # 将实例加入类列表
        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:
            Item(
                name=item.get('name'),
                price=int(item.get('price', 0)),
                quantity=int(item.get('quantity', 0)),
            )

        
    def __repr__(self):
        return f"Item('{self.name}', '{self.price}', '{self.quantity}')"

Item.instantiate_from_csv()
print(Item.all)

运行修改后的代码和CSV文件,就能正常实例化Item对象并输出结果了。

内容的提问来源于stack exchange,提问作者Spike1801

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 22:04:57