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

Python使用append()存储车辆数据仅保留最后一条记录问题求助

问题根因

你遇到的“仅保留最后一条数据”的现象和append()方法无关,列表car_description里已经正确存储了所有录入的车辆对象,错误出在打印逻辑:
你在遍历car_description时,循环变量定义为vehicle,但实际打印时调用的是car变量的属性,而car变量保存的是最后一次录入时返回的车辆对象,所以遍历多少次都会打印同一条最后录入的数据。

代码其他不规范问题
  • CARDATA类定义时属性未缩进,属于全局变量而非类属性,不符合类定义的语法规范
  • 类属性直接声明的写法容易引发实例属性共享的潜在问题,建议用构造方法初始化实例属性
  • 缺少退出选项,程序会无限循环
修复后完整代码
class CARDATA:
    # 用构造方法初始化实例属性
    def __init__(self):
        self.brand = ""
        self.price = 0

def menu():
    print("1) Input car data")
    print("2) Print car data")
    print("3) Exit")
    option = int(input("Your pick was: "))
    return option

def car_object(car_description):
    car = CARDATA() 
    car.brand = input("Car make?: ")
    car.price = int(input("Listed price? "))
    car_description.append(car)
    return car

def main():
    car_description = []
    while (True):
        selection = menu()
        if (selection == 1):
            car = car_object(car_description)
        elif (selection == 2):
            print("Car makes and selling prices on the list:")
            for vehicle in car_description:
                # 修正打印变量,用当前迭代的vehicle对象
                print(vehicle.brand, vehicle.price)
        elif (selection == 3):
            print("Exit program")
            break
    return car_description

main()
核心修复点
  • 打印逻辑修正:将打印变量从car改为循环变量vehicle,正确输出列表中每个车辆对象的属性
  • 规范CARDATA类的定义,补充构造方法初始化实例属性
  • 新增退出选项,优化程序交互逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 03:54:04