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

Python实现用户自定义记录时出现AttributeError问题求助

问题排查与解决:自定义记录类的AttributeError错误

错误原因分析

出现AttributeError: 'user_class' object has no attribute 'feild_list'的核心原因是:

  • 类的__init__方法中直接尝试给self.feild_list[i]赋值,但从未初始化self.feild_list这个属性,Python找不到该属性就会抛出错误。
  • 额外存在的问题:
    1. 拼写错误:所有feild应为field(英文字段的正确拼写)。
    2. 类定义嵌套在if分支内部,不符合代码规范,且不利于后续复用。
    3. 参数命名混淆:创建实例时传入fact_list,但类的__init__参数名是feild_list,逻辑不清晰。
    4. 无效的循环判断:while choice != "Y" or choice != "N"逻辑错误,无论输入什么都会进入循环,应改为and。

修正步骤

  1. 初始化类属性:在__init__方法中先创建self.field_list属性,再进行赋值操作,或者直接将传入的列表赋值给它。
  2. 修正拼写错误:统一替换所有feild为field。
  3. 调整类的位置:将user_class的定义移到代码最外层,避免分支内定义类的问题。
  4. 理清参数命名:让类的参数名与传入的实际数据对应,增强代码可读性。
  5. 修复循环逻辑:将while条件中的or改为and,确保只有输入非Y/N时才进入循环。

完整修正代码

user_list = []

class UserRecord:
    def __init__(self, record_data):
        # 直接初始化并赋值字段列表
        self.field_list = record_data

choice = input("Enter choice (Y/N):")

while choice not in ["Y", "N"]:
    print("Invalid choice")
    choice = input("Enter choice (Y/N):")

while choice == "Y":
    field_list = []
    record_length = int(input("Enter record length:"))
    
    for i in range(record_length):
        field = input("Enter a field:")
        field_list.append(field)
    
    fact_list = []
    for field in field_list:
        fact = input(f"Enter value for {field}:")
        fact_list.append(fact)
    
    record = UserRecord(fact_list)
    user_list.append(record)
    
    # 打印更易读的记录内容
    print("Current records:")
    for idx, rec in enumerate(user_list):
        print(f"Record {idx+1}: {dict(zip(field_list, rec.field_list))}")
    
    choice = input("Enter choice (Y/N):")
    # 再次校验输入有效性
    while choice not in ["Y", "N"]:
        print("Invalid choice")
        choice = input("Enter choice (Y/N):")

if choice == "N":
    print("Program Ended.")

额外优化说明

  • 将类名改为UserRecord,符合Python大驼峰命名规范。
  • 打印记录时用dict(zip(field_list, rec.field_list))将字段名和值配对成字典,输出更直观。
  • 重构了输入校验逻辑,避免冗余代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 03:10:24