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

Python类中存储车辆数据及查询过滤实现方法咨询

实现预存数据的Vehicle类及搜索过滤功能

1. 实现Vehicle(2).hp的查询方式

Python里可以通过类静态属性存储预存数据,实例化时传入索引(兼容MATLAB的1起始习惯),然后把对应数据的字段绑定为实例属性,就能直接通过.访问:

class Vehicle:
    # 预存车辆数据,按顺序存储,每个元素是包含车辆信息的字典
    _vehicle_data = [
        {"id": 1, "hp": 150, "type": "sedan", "brand": "Toyota"},
        {"id": 2, "hp": 220, "type": "SUV", "brand": "Honda"},
        {"id": 3, "hp": 300, "type": "sports_car", "brand": "BMW"}
    ]

    def __init__(self, index):
        # 转成Python的0起始索引,若习惯纯0起始可删除此行
        data_idx = index - 1
        if data_idx < 0 or data_idx >= len(self._vehicle_data):
            raise IndexError("车辆索引超出范围")
        # 把数据里的键值对设为实例属性
        for key, value in self._vehicle_data[data_idx].items():
            setattr(self, key, value)

使用示例:

veh = Vehicle(2)
print(veh.hp)       # 输出 220
print(veh.brand)    # 输出 Honda

2. 实现数据的搜索与过滤

给类添加类方法(无需实例化即可调用),直接操作预存的静态数据,返回符合条件的Vehicle实例:

class Vehicle:
    _vehicle_data = [
        {"id": 1, "hp": 150, "type": "sedan", "brand": "Toyota"},
        {"id": 2, "hp": 220, "type": "SUV", "brand": "Honda"},
        {"id": 3, "hp": 300, "type": "sports_car", "brand": "BMW"},
        {"id": 4, "hp": 180, "type": "sedan", "brand": "Ford"}
    ]

    def __init__(self, index):
        data_idx = index - 1
        if data_idx < 0 or data_idx >= len(self._vehicle_data):
            raise IndexError("车辆索引超出范围")
        for key, value in self._vehicle_data[data_idx].items():
            setattr(self, key, value)
    
    @classmethod
    def search_by_brand(cls, target_brand):
        """按品牌搜索,返回匹配的Vehicle实例列表"""
        matches = []
        # 遍历数据,用enumerate获取1起始的索引
        for idx, info in enumerate(cls._vehicle_data, start=1):
            if info["brand"].lower() == target_brand.lower():
                matches.append(Vehicle(idx))
        return matches
    
    @classmethod
    def filter_by_hp(cls, min_hp, max_hp=None):
        """按马力过滤,可只传最小值(返回>=min_hp的车辆)"""
        matches = []
        for idx, info in enumerate(cls._vehicle_data, start=1):
            hp = info["hp"]
            if max_hp is None:
                if hp >= min_hp:
                    matches.append(Vehicle(idx))
            else:
                if min_hp <= hp <= max_hp:
                    matches.append(Vehicle(idx))
        return matches

搜索过滤示例:

# 搜索所有丰田车
toyota_cars = Vehicle.search_by_brand("Toyota")
for car in toyota_cars:
    print(f"ID: {car.id}, 马力: {car.hp}")  # 输出 ID: 1, 马力: 150

# 过滤马力200及以上的车
high_hp_cars = Vehicle.filter_by_hp(200)
for car in high_hp_cars:
    print(f"车型: {car.type}, 品牌: {car.brand}")  # 输出 车型: SUV, 品牌: Honda;车型: sports_car, 品牌: BMW

# 过滤马力150-200之间的车
mid_hp_cars = Vehicle.filter_by_hp(150, 200)
for car in mid_hp_cars:
    print(f"ID: {car.id}, 马力: {car.hp}")  # 输出 ID: 1, 马力: 150;ID: 4, 马力: 180

3. 扩展:动态添加车辆数据

如果需要后续更新数据,可以加个类方法来添加新车:

@classmethod
def add_vehicle(cls, new_vehicle):
    """添加新车,自动生成唯一ID"""
    max_id = max(info["id"] for info in cls._vehicle_data) if cls._vehicle_data else 0
    new_vehicle["id"] = max_id + 1
    cls._vehicle_data.append(new_vehicle)

# 使用示例
Vehicle.add_vehicle({"hp": 250, "type": "SUV", "brand": "Tesla"})
new_veh = Vehicle(5)
print(new_veh.hp)  # 输出 250

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 23:45:45