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

Python读取TXT生成类对象列表时遇UnboundLocalError问题求助

问题分析与修复方案

核心错误:UnboundLocalError

你在函数read_record_data里直接修改全局变量list_of_records,但没有声明它是全局变量。Python会默认把函数内赋值的变量当成局部变量,导致第一次循环时引用list_of_records(赋值操作list_of_records = list_of_records + [item]里的右边)时,局部变量还未定义,触发UnboundLocalError。

其他代码问题

  1. Vinyl类初始化遗漏参数:__init__方法接收了quantity参数,但没有给实例绑定这个属性,会导致实例缺少quantity属性。
  2. 多余的解包变量:拆分每行数据后,你解包出了cself,但你的数据里应该没有这个字段,会触发ValueError(字段数量不匹配)。
  3. 错误遍历Vinyl对象:Vinyl实例不是可迭代对象,for item in record_entry会直接触发TypeError,根本不需要遍历,直接把整个实例加入列表即可。
  4. 文件未安全关闭:直接用open打开文件,没有手动关闭或用with语句,可能导致文件资源泄漏。

修正后的代码

首先修正Vinyl类:

class Vinyl:
    def __init__(self, artist, album, size, cost, quantity):
        self.artist = artist
        self.album = album
        self.size = size
        self.cost = cost
        self.quantity = quantity  # 新增:绑定quantity属性

然后修正读取函数:

list_of_records = []

def read_record_data():
    global list_of_records  # 声明使用全局变量
    # 用with语句自动管理文件
    with open("inventory.txt", "r", encoding='utf-8') as file_read:
        for line in file_read:
            row = line.strip().split(",")  # 先整行去首尾空白,再拆分
            # 去掉多余的cself,匹配5个字段
            artist, album, size, cost, quantity = [i.strip() for i in row]
            record_entry = Vinyl(artist, album, size, cost, quantity)
            # 直接添加整个实例到列表,不需要遍历
            list_of_records.append(record_entry)

额外建议

如果不想用全局变量,可以让函数返回处理后的列表,这样代码更模块化:

def read_record_data():
    list_of_records = []
    with open("inventory.txt", "r", encoding='utf-8') as file_read:
        for line in file_read:
            row = line.strip().split(",")
            artist, album, size, cost, quantity = [i.strip() for i in row]
            record_entry = Vinyl(artist, album, size, cost, quantity)
            list_of_records.append(record_entry)
    return list_of_records

# 调用时接收返回值
inventory = read_record_data()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 06:25:10