Python父类子类分组打印汽车库存数据问题求助
汽车库存规整打印问题解决
我通过父类Car与子类ImportCar、DomesticCar实现汽车库存文件的规整打印,已为各子类分配打印逻辑,但无法让Python将以相同标识(I/D)开头的行合并输出(如预期输出所示)。尝试将i_car和d_car放入for循环仍未解决,推测是if语句参数或变量赋值位置存在问题。
现有代码
class Car: def __init__(self, brand, model, year, price, type): self.brand = brand self.model = model self.year = year self.price = price self.type = type def print_info(self): print(self.brand, self.model, self.year, self.price, self.type) class ImportCar(Car): def __init__(self, brand, model, year, price, type, country, tax): super().__init__(brand, model, year, price, type) self.country = country self.tax = tax def print_info(self): print(self.brand, self.model, self.year, self.price, self.type, self.country, self.tax) class DomesticCar(Car): def __init__(self, brand, model, year, price, type, state): super().__init__(brand, model, year, price, type) self.state = state def print_info(self): print(self.brand, self.model, self.year, self.price, self.type, self.state) with open("carsInStock.txt", "r") as f: for line in f: val = line.split() i_car = ImportCar(val[0], val[1], val[2], val[3], val[4], val[5], val[6]) d_car = DomesticCar(val[0], val[1], val[2], val[3], val[4], val[5]) for i in range(len(val)): if val[0] == "I": print("Lines starting with I: ", i_car.print_info()) break; elif val[0] == "D": print("Lines starting with D: ", d_car.print_info()) break; else: print("Error")
库存文件内容
D Ford F150 2012 17000 Truck MI I Toyota Camry 2014 20000 Sedan Japan 10 D Chrysler Pacifica 2013 18000 Sedan TX I BMW 325i 2013 30000 Sedan Germany 8 D Chevrolet TahoeLS 2010 7000 Coup TX D Chevrolet Silverado 2011 10000 Van MI I Toyota LexusRX30 2015 42000 Sedan Japan 10 D Ford Econoline 2012 16000 Sedan MI
当前错误输出
D Ford F150 2012 17000 Truck Lines starting with D: None I Toyota Camry 2014 20000 Sedan Japan Lines starting with I: None D Chrysler Pacifica 2013 18000 Sedan Lines starting with D: None I BMW 325i 2013 30000 Sedan Germany Lines starting with I: None D Chevrolet TahoeLS 2010 7000 Coup Lines starting with D: None D Chevrolet Silverado 2011 10000 Van Lines starting with D: None I Toyota LexusRX30 2015 42000 Sedan Japan Lines starting with I: None D Ford Econoline 2012 16000 Sedan Lines starting with D: None
预期输出
Lines starting with I: Toyota Camry 2014 2000 Sedan Japan 10% BMW 325i 2013 30000 Sedan Germany 8% Toyota LexusRX30 2015 42000 Sedan Japan 10% Lines starting with D: Ford F150 2012 17000 Truck MI Chrysler Pacifica 2013 18000 Sedan TX Chevrolet TahoeLS 2010 7000 Coup TX Chevrolet Silverado 2011 10000 Van MI Ford Econoline 2012 16000 Sedan MI Number of I cars = 3 Number of D cars = 5 Total = 8
问题分析
- 实例创建逻辑错误:每行都强制创建
ImportCar和DomesticCar实例,D开头行的参数数量不足以创建ImportCar,逻辑冗余且存在报错风险;同时错误地将标识I/D传给了brand参数。 - 输出逻辑错误:
print_info方法直接执行打印操作,返回值为None,导致外层print额外输出None;且每行都重复打印分类标题,不符合合并输出要求。 - 数据未分类存储:未提前将进口车和国产车分类存储,无法实现统一批量输出。
修正后的代码
class Car: def __init__(self, brand, model, year, price, car_type): self.brand = brand self.model = model self.year = year self.price = price self.car_type = car_type def get_info(self): return f"{self.brand} {self.model} {self.year} {self.price} {self.car_type}" class ImportCar(Car): def __init__(self, brand, model, year, price, car_type, country, tax): super().__init__(brand, model, year, price, car_type) self.country = country self.tax = tax def get_info(self): return f"{super().get_info()} {self.country} {self.tax}%" class DomesticCar(Car): def __init__(self, brand, model, year, price, car_type, state): super().__init__(brand, model, year, price, car_type) self.state = state def get_info(self): return f"{super().get_info()} {self.state}" # 初始化列表分类存储车辆 import_cars = [] domestic_cars = [] with open("carsInStock.txt", "r") as f: for line in f: val = line.strip().split() if not val: continue # 跳过空行 # 根据标识创建对应实例并分类存储 if val[0] == "I": car = ImportCar(val[1], val[2], val[3], val[4], val[5], val[6], val[7]) import_cars.append(car) elif val[0] == "D": car = DomesticCar(val[1], val[2], val[3], val[4], val[5], val[6]) domestic_cars.append(car) else: print(f"无效行:{line}") # 统一打印分类结果 print("Lines starting with I:") for car in import_cars: print(car.get_info()) print("\nLines starting with D:") for car in domestic_cars: print(car.get_info()) # 打印统计信息 print(f"\nNumber of I cars = {len(import_cars)}") print(f"Number of D cars = {len(domestic_cars)}") print(f"Total = {len(import_cars) + len(domestic_cars)}")
修改说明
- 重构输出方法:将
print_info改为get_info,返回格式化字符串而非直接打印,让输出逻辑更灵活可控。 - 分类存储数据:用两个列表分别存储进口车和国产车实例,实现统一批量输出。
- 修正实例参数:正确提取行内数据,将标识
I/D与车辆属性分离,避免参数传递错误。 - 补充格式要求:为进口车税率添加
%符号,匹配预期输出格式。 - 添加统计逻辑:通过列表长度直接统计各类车辆数量及总数。
内容的提问来源于stack exchange,提问作者EggCoder
相关产品推荐
相关产品推荐

