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

修复Python类递归继承次数统计代码:解决仅支持一级继承问题

修复递归统计Python类继承次数的方案

你的代码仅能统计直接继承的关系,要实现递归统计间接继承,需要先完整收集所有类的继承关系,再通过递归遍历处理间接层级。以下是分步骤的修复方案:

1. 先收集所有类的继承关系

首先遍历所有Python文件,提取每个类的名称及其直接基类(排除object,处理多基类场景),构建继承关系映射:

import os

def collect_class_inheritance(project_path):
    # 键:类名,值:该类的直接基类列表(已排除object)
    class_inheritance = {}
    
    for root, _, files in os.walk(project_path):
        for file in files:
            if not file.endswith(".py"):
                continue
            file_path = os.path.join(root, file)
            with open(file_path, "r", encoding="utf-8") as f:
                for line in f:
                    stripped_line = line.strip()
                    # 匹配类定义行(处理带括号的继承场景)
                    if stripped_line.startswith("class") and "(" in stripped_line and ":" in stripped_line:
                        # 拆分类名和基类部分
                        class_def = stripped_line.split("class")[1].split(":")[0].strip()
                        class_name = class_def.split("(")[0].strip()
                        bases_section = class_def.split("(")[1].split(")")[0].strip()
                        
                        # 处理多基类,过滤掉object
                        base_classes = []
                        if bases_section:
                            base_classes = [
                                base.strip() 
                                for base in bases_section.split(",") 
                                if base.strip() and base.strip() != "object"
                            ]
                        class_inheritance[class_name] = base_classes
    return class_inheritance

2. 递归统计目标数据

根据你的需求,分两种常见场景实现:

场景A:统计每个类被直接/间接继承的总次数

比如你的例子中,D会被A间接继承,所以D的被继承次数为1;B被A直接继承,次数为1;C被A直接继承,次数为1。

def count_total_inherited_times(class_inheritance):
    # 反向构建继承映射:键为基类,值为直接子类列表
    reverse_inheritance = {}
    for cls, bases in class_inheritance.items():
        for base in bases:
            if base not in reverse_inheritance:
                reverse_inheritance[base] = []
            reverse_inheritance[base].append(cls)
    
    inherited_count = {}
    
    # 递归统计当前类的所有直接/间接子类数量
    def recursive_count(cls):
        total = 0
        # 直接子类数量
        direct_children = reverse_inheritance.get(cls, [])
        total += len(direct_children)
        # 递归累加每个子类的子类数量
        for child in direct_children:
            total += recursive_count(child)
        return total
    
    # 为每个类计算总被继承次数
    for cls in class_inheritance.keys():
        inherited_count[cls] = recursive_count(cls)
    
    return inherited_count

场景B:统计每个类的继承深度(即到最顶层非object类的最长层级)

比如你的例子中,A的继承深度为2(A→B→D,共2次继承跳转);B的深度为1;D和C的深度为0。

def count_inheritance_depth(class_inheritance):
    depth_map = {}
    
    # 递归计算当前类的继承深度
    def get_depth(cls):
        if cls in depth_map:
            return depth_map[cls]
        bases = class_inheritance.get(cls, [])
        if not bases:
            # 没有基类,深度为0
            depth = 0
        else:
            # 取所有基类的最大深度 +1
            max_base_depth = max(get_depth(base) for base in bases)
            depth = max_base_depth + 1
        depth_map[cls] = depth
        return depth
    
    # 为每个类计算深度
    for cls in class_inheritance.keys():
        get_depth(cls)
    
    return depth_map

3. 调用示例

# 替换为你的项目路径
project_path = "./your_python_project"
inheritance_map = collect_class_inheritance(project_path)

# 统计被继承总次数
total_inherited = count_total_inherited_times(inheritance_map)
print("类被继承总次数:", total_inherited)

# 统计继承深度
depth_counts = count_inheritance_depth(inheritance_map)
print("类继承深度:", depth_counts)

原代码的问题分析

  1. 仅处理直接继承:没有构建完整的继承关系链,无法递归处理间接继承的层级。
  2. 多基类处理错误:没有拆分逗号分隔的多个基类,会把B, C当作一个基类处理。
  3. 变量不规范:count变量未初始化且依赖全局作用域,代码健壮性差。
  4. 未过滤object:会把object当作有效基类统计,不符合Python继承的顶层逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 00:41:14