如何采用面向对象(OOP)框架构建汽车数据查询项目?
汽车数据项目OOP结构搭建方案
项目目录结构
先梳理清晰的分层目录,便于维护和扩展:
car-data-project/ ├── models/ # 实体类,对应核心业务对象 │ ├── __init__.py │ ├── car.py │ ├── component.py │ └── manufacturer.py ├── data_access/ # 数据访问层,专门处理CSV读写逻辑 │ ├── __init__.py │ └── csv_data_handler.py ├── services/ # 业务逻辑层,封装核心功能 │ ├── __init__.py │ ├── car_search_service.py │ └── manufacturer_service.py ├── main.py # 项目入口,用于功能演示和调用 └── data/ # 存放CSV数据文件 ├── cars.csv ├── components.csv └── manufacturers.csv
各模块职责与代码示例
1. 模型层(models/)
定义核心业务实体,封装属性和基础行为,对应真实业务对象。
- component.py:部件实体,关联编号与名称
class Component: def __init__(self, component_id: str, name: str): self.component_id = component_id self.name = name def __repr__(self): return f"Component(id={self.component_id}, name={self.name})"
- manufacturer.py:制造商实体,封装详情信息
class Manufacturer: def __init__(self, manufacturer_id: str, name: str, country: str, founded_year: int): self.manufacturer_id = manufacturer_id self.name = name self.country = country self.founded_year = founded_year def get_details(self) -> str: return f"制造商:{self.name},来自{self.country},成立于{self.founded_year}年"
- car.py:车型实体,关联制造商与部件
from models.component import Component from models.manufacturer import Manufacturer class Car: def __init__(self, car_id: str, model_name: str, hp: int, manufacturer: Manufacturer, components: list[Component]): self.car_id = car_id self.model_name = model_name self.hp = hp self.manufacturer = manufacturer self.components = components def has_component(self, component_id: str) -> bool: return any(comp.component_id == component_id for comp in self.components) def get_basic_info(self) -> str: return f"车型:{self.model_name},马力:{self.hp},制造商:{self.manufacturer.name}"
2. 数据访问层(data_access/)
隔离数据格式与业务逻辑,专门负责从CSV读取数据并转换为模型对象。
csv_data_handler.py:
import csv from models.car import Car from models.component import Component from models.manufacturer import Manufacturer class CSVDataHandler: def __init__(self, data_dir: str = "data"): self.data_dir = data_dir def load_components(self) -> dict[str, Component]: components = {} with open(f"{self.data_dir}/components.csv", mode="r", encoding="utf-8") as f: reader = csv.DictReader(f) for row in reader: comp = Component(row["component_id"], row["name"]) components[comp.component_id] = comp return components def load_manufacturers(self) -> dict[str, Manufacturer]: manufacturers = {} with open(f"{self.data_dir}/manufacturers.csv", mode="r", encoding="utf-8") as f: reader = csv.DictReader(f) for row in reader: manu = Manufacturer( row["manufacturer_id"], row["name"], row["country"], int(row["founded_year"]) ) manufacturers[manu.manufacturer_id] = manu return manufacturers def load_cars(self, components: dict[str, Component], manufacturers: dict[str, Manufacturer]) -> list[Car]: cars = [] with open(f"{self.data_dir}/cars.csv", mode="r", encoding="utf-8") as f: reader = csv.DictReader(f) for row in reader: # 假设cars.csv中部件编号用逗号分隔,如"43,12,56" component_ids = row["component_ids"].split(",") car_components = [components[cid.strip()] for cid in component_ids if cid.strip() in components] manufacturer = manufacturers.get(row["manufacturer_id"]) if manufacturer: car = Car( row["car_id"], row["model_name"], int(row["hp"]), manufacturer, car_components ) cars.append(car) return cars
3. 业务逻辑层(services/)
封装核心业务功能,调用数据层获取数据并处理业务规则,对上层提供简洁接口。
car_search_service.py:
from models.car import Car from data_access.csv_data_handler import CSVDataHandler class CarSearchService: def __init__(self): self.data_handler = CSVDataHandler() # 提前加载数据,也可按需延迟加载 self.components = self.data_handler.load_components() self.manufacturers = self.data_handler.load_manufacturers() self.cars = self.data_handler.load_cars(self.components, self.manufacturers) def search_cars_by_component_id(self, component_id: str) -> list[Car]: return [car for car in self.cars if car.has_component(component_id)] def get_car_full_details(self, car: Car) -> str: component_names = ", ".join(comp.name for comp in car.components) return f"""{car.get_basic_info()} 包含部件:{component_names} {car.manufacturer.get_details()}"""
manufacturer_service.py(为未来需求预留):
from models.car import Car from models.manufacturer import Manufacturer from data_access.csv_data_handler import CSVDataHandler class ManufacturerService: def __init__(self): self.data_handler = CSVDataHandler() self.components = self.data_handler.load_components() self.manufacturers = self.data_handler.load_manufacturers() self.cars = self.data_handler.load_cars(self.components, self.manufacturers) def get_manufacturer_cars(self, manufacturer_id: str) -> list[Car]: manu = self.manufacturers.get(manufacturer_id) if not manu: return [] return [car for car in self.cars if car.manufacturer.manufacturer_id == manufacturer_id] def get_manufacturer_full_details(self, manufacturer_id: str) -> str: manu = self.manufacturers.get(manufacturer_id) if not manu: return "未找到该制造商信息" car_count = len(self.get_manufacturer_cars(manufacturer_id)) return f"""{manu.get_details()} 旗下车型数量:{car_count}"""
4. 入口文件(main.py)
作为项目启动点,演示核心功能调用:
from services.car_search_service import CarSearchService if __name__ == "__main__": search_service = CarSearchService() # 搜索包含部件编号43的车型 target_component_id = "43" matching_cars = search_service.search_cars_by_component_id(target_component_id) print(f"找到包含部件{target_component_id}的车型:") for idx, car in enumerate(matching_cars, 1): print(f"\n车型{idx}:") print(search_service.get_car_full_details(car))
设计思路说明
- 单一职责:每个类只负责一件事,比如
CSVDataHandler仅处理CSV读写,CarSearchService仅处理车型搜索,修改某模块不会影响其他功能。 - 可扩展性:未来新增按HP筛选、制造商销量统计等功能时,只需在对应服务类添加方法,或新增模型/服务模块,无需改动现有代码。
- 可读性:实体与逻辑分离,新人接手能快速理解各模块角色,降低维护成本。
内容的提问来源于stack exchange,提问作者Shesch
相关产品推荐
相关产品推荐

