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

在Vehicles类中实现filter方法筛选指定类的车辆对象

解决方案

实现思路

  • 在Vehicles主类中定义静态方法filter,接收两个参数:待遍历的车辆列表vehicle_list和目标筛选类target_class
  • 通过isinstance()判断列表中每个对象是否属于目标类,收集到结果列表
  • 格式化输出指定格式的字符串,确保实例显示为要求的名称(如car1)

完整代码实现

class Vehicles:
    @staticmethod
    def filter(vehicle_list, target_class):
        # 筛选目标类的所有实例
        matched_vehicles = [veh for veh in vehicle_list if isinstance(veh, target_class)]
        # 转换为实例名称字符串,依赖子类的__repr__定义
        veh_names = [repr(veh) for veh in matched_vehicles]
        # 按要求格式打印
        print(f"From the list all_vehicles were found [{', '.join(veh_names)}]")

# 完善子类定义,添加__repr__确保输出正确名称
class Car(Vehicles):
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return self.name

class Truck(Vehicles):
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return self.name

class Bike(Vehicles):
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return self.name

class Motorbike(Vehicles):
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return self.name

# 测试用例
car1 = Car("car1")
car2 = Car("car2")
car3 = Car("car3")
truck1 = Truck("truck1")
bike1 = Bike("bike1")

all_vehicles = [car1, car2, truck1, car3, bike1]

# 调用筛选方法,示例:筛选所有Car实例
Vehicles.filter(all_vehicles, Car)

关键说明

  1. 静态方法的使用:不需要实例化Vehicles类,直接通过Vehicles.filter()调用,符合工具方法的定位
  2. 类型判断:isinstance()能正确识别子类实例(如果后续有继承自Car的子类,也会被筛选),如果需要严格匹配当前类而非子类,可改用type(veh) == target_class
  3. 名称显示:子类中重写__repr__方法,确保打印实例时直接输出自定义名称,完全匹配要求的输出格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 03:25:29