如何在Garage类中批量添加多个Car类实例对象?
嘿,我来帮你搞定这个问题!你的代码已经搭建好了Car和Garage的基础框架,现在要添加多辆Car其实很简单,我给你几种实用的方案:
解决方案
方法1:多次调用现有addcars方法
这是最直接的方式——既然现有addcars方法一次能添加一辆车,那我们只需要创建多个Car实例,分别调用方法就行:
class Car: def __init__(self, make, model): self.make = make self.model = model def __repr__(self): return f'<Car {self.make} {self.model}>' class Garage: def __init__(self): self.cars = [] def __len__(self): return len(self.cars) def addcars(self, car): if not isinstance(car, Car): raise TypeError('you should pass only instance of the class car') self.cars.append(car) g = Garage() # 创建第一辆车并添加 car1 = Car('ford', 'fogo') g.addcars(car1) # 创建第二辆车并添加 car2 = Car('toyota', 'camry') g.addcars(car2) # 查看车库状态 print(len(g)) # 输出:2 print(g.cars) # 输出:[<Car ford fogo>, <Car toyota camry>]
小提醒:你原来的print(g.addcars(car))会输出None,因为addcars方法没有返回值,直接调用g.addcars(car)就好,不用打印它的结果~
方法2:修改addcars方法支持批量添加
如果以后经常需要批量加车,我们可以修改addcars方法,让它能接收多个Car实例参数,用Python的*args实现:
class Car: def __init__(self, make, model): self.make = make self.model = model def __repr__(self): return f'<Car {self.make} {self.model}>' class Garage: def __init__(self): self.cars = [] def __len__(self): return len(self.cars) def addcars(self, *args): # 用*args接收任意数量的参数 for car in args: if not isinstance(car, Car): raise TypeError('you should pass only instance of the class car') self.cars.append(car) g = Garage() # 方式1:先创建实例再传入 car1 = Car('ford', 'fogo') car2 = Car('honda', 'civic') g.addcars(car1, car2) # 方式2:直接在调用时创建实例,更简洁 g.addcars(Car('bmw', '3-series'), Car('audi', 'a4')) print(len(g)) # 输出:4 print(g.cars)
修改后,addcars既可以加一辆车,也能一次加N辆,灵活性拉满。
方法3:新增专门的批量添加方法
如果你不想改动原有addcars方法的逻辑,也可以给Garage类新增一个批量添加的方法,复用原有检查逻辑:
class Car: def __init__(self, make, model): self.make = make self.model = model def __repr__(self): return f'<Car {self.make} {self.model}>' class Garage: def __init__(self): self.cars = [] def __len__(self): return len(self.cars) def addcars(self, car): if not isinstance(car, Car): raise TypeError('you should pass only instance of the class car') self.cars.append(car) def add_multiple_cars(self, car_list): # 接收一个Car实例的列表 for car in car_list: self.addcars(car) # 复用原有addcars的检查逻辑,不用重复写代码 g = Garage() # 创建一个包含多辆Car的列表 car_list = [ Car('ford', 'fogo'), Car('mazda', 'mx-5'), Car('subaru', 'wrx') ] g.add_multiple_cars(car_list) print(len(g)) # 输出:3 print(g.cars)
这种方式保留了原有方法的功能,同时新增了批量操作能力,代码复用性更好。
内容的提问来源于stack exchange,提问作者Madhumathi
相关产品推荐
相关产品推荐

