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

Python管理对象列表的类编写最佳实践及UML图关联方法

代码实现优化建议

现有实现已经满足基础功能,可从以下几个方向优化可用性和可维护性:

  • 修正拼写错误:类名IngredentsList、方法名addIngredent存在拼写错误,正确拼写为IngredientsList、addIngredient,避免后续调用时因为拼写问题出bug
  • 调整继承逻辑为组合逻辑(可选):现有IngredientQuantity继承自Ingredient的设计,会导致同一个食材每次被使用时都要重复传入名称、单位参数,浪费存储空间也容易出现输入不一致的问题。可以改成Ingredient存储食材元数据(名称、单位),IngredientQuantity组合Ingredient实例+用量数值,同一个食材的元数据可以全局复用
  • 增加类型校验:在addIngredient方法中增加参数类型校验,避免传入非预期对象时报错信息不明确
  • 优化字符串输出:给IngredientQuantity实现__str__魔法方法,无需每次手动拼接输出字符串
  • 扩展列表管理能力:可以给IngredientsList增加按名称查询食材、统计总重量、迭代遍历等常用方法,降低后续业务逻辑的编码成本

下面是优化后的示例代码:

class Ingredient:
    """食材元数据类,存储食材的通用属性"""
    def __init__(self, name: str, measure: str):
        self.name = name
        self.measure = measure

class IngredientQuantity:
    """带用量的食材条目类"""
    def __init__(self, ingredient: Ingredient, quantity: float):
        self.ingredient = ingredient
        self.quantity = quantity
    
    def __str__(self):
        return f"{self.quantity} {self.ingredient.measure} 的 {self.ingredient.name}"

class IngredientsList:
    """食材列表管理类"""
    def __init__(self):
        self._ingredients = []
    
    def add_ingredient(self, ingredient_quantity: IngredientQuantity) -> None:
        if not isinstance(ingredient_quantity, IngredientQuantity):
            raise TypeError("仅支持添加IngredientQuantity类型的实例")
        print(f"正在添加{ingredient_quantity}...")
        self._ingredients.append(ingredient_quantity)
    
    # 扩展:按名称查找食材用量
    def get_by_name(self, name: str) -> IngredientQuantity | None:
        for item in self._ingredients:
            if item.ingredient.name == name:
                return item
        return None
    
    def __len__(self):
        return len(self._ingredients)

调用示例:

# 先定义通用食材元数据,可全局复用
egg = Ingredient("鸡蛋", "个")
flour = Ingredient("低筋面粉", "g")

ilist = IngredientsList()
ilist.add_ingredient(IngredientQuantity(egg, 2))
ilist.add_ingredient(IngredientQuantity(flour, 100))
UML类关系说明

没有继承关系的类也完全可以加入UML类图,类之间的关联不只有继承一种,你的现有类对应的UML关系如下:

  • 原继承设计下:IngredientQuantity和Ingredient是泛化(继承)关系,用空心三角形的连线指向父类Ingredient即可
  • IngredientsList和IngredientQuantity是聚合关系(关联的一种),表示1个食材列表可以包含0个或多个带用量的食材实例,UML中用带空心菱形的连线指向IngredientsList,连线两端分别标注基数1(1个列表)和0..*(0到多个食材条目)
  • 如果采用上面优化后的组合设计,IngredientQuantity和Ingredient是关联关系,连线两端标注基数1(1个用量条目对应1个食材元数据)和0..*(1个食材元数据可以对应多个用量条目)
  • 后续如果扩展其他类,比如食谱类Recipe可以关联1个IngredientsList,蛋糕类Cake可以关联1个Recipe,整个系统的类关系就可以完全串联起来

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 00:15:03