Python类内调用classmethod问题:实例化重复计数如何解决?
解决Python类中实例化时重复累加计数的问题
你的代码核心问题是在__init__方法中每次实例化都调用count_material,而这个方法会遍历整个materials列表重新统计——每新增一个实例,列表长度增加1,统计时会把之前所有元素再数一遍,导致重复累加。比如:
- 第一次实例化后,
materials = ["Wood"],统计后Wood计数为1; - 第二次实例化后,
materials = ["Wood", "Cotton"],统计时会再次遍历Wood和Cotton,Wood变成2,Cotton变成1; - 第三次实例化后,
materials有3个元素,前两个元素又被多统计一次,最终出现{'Wood': 3, 'Cotton': 2, 'Glass': 1}的错误结果。
方案一:仅在所有实例创建完成后调用统计方法
修改代码,把__init__里的统计调用移除,只在所有实例化完成后执行一次统计:
class Furniture: materials = [] material_count = {} def __init__(self, name, material): self.name = name self.material = material Furniture.materials.append(self.material) @classmethod def count_material(cls): # 先清空旧计数,避免重复统计 cls.material_count.clear() for material in cls.materials: cls.material_count[material] = cls.material_count.get(material, 0) + 1 # 创建所有实例 Furniture("Chair", "Wood") Furniture("Cushion", "Cotton") Furniture("Table", "Glass") # 仅调用一次统计方法 Furniture.count_material() print(Furniture.material_count) # 输出: {'Wood': 1, 'Cotton': 1, 'Glass': 1}
方案二:添加材质时直接更新计数(更高效)
不需要维护materials列表,直接在实例化时更新计数,避免重复遍历:
class Furniture: material_count = {} def __init__(self, name, material): self.name = name self.material = material # 直接将该材质计数设为1(同一材质多次实例化也只算1次) Furniture.material_count[material] = 1 # 如果需要统计同一材质的实例数量(多次实例化累加),则替换为: # Furniture.material_count[material] = Furniture.material_count.get(material, 0) + 1 Furniture("Chair", "Wood") Furniture("Cushion", "Cotton") Furniture("Table", "Glass") print(Furniture.material_count) # 输出: {'Wood': 1, 'Cotton': 1, 'Glass': 1}
内容的提问来源于stack exchange,提问作者Michael Mumo
相关产品推荐
相关产品推荐

