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

如何列出指定.py文件中的所有类、方法及函数?

提取Python文件中的函数与类方法方案

核心思路

直接通过importlib加载目标文件为临时模块,再用inspect模块分析模块结构,区分模块级函数、类及类内方法,最终按要求格式输出。

完整实现代码

import importlib.util
import inspect

def get_functions_and_methods(file_path):
    # 加载目标文件为临时模块
    spec = importlib.util.spec_from_file_location("temp_module", file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    
    output = []
    
    # 遍历模块所有成员
    for name, member in inspect.getmembers(module):
        # 提取模块级公开函数(排除双下划线开头的内置成员)
        if inspect.isfunction(member) and not name.startswith('__'):
            sig = inspect.signature(member)
            output.append(f"'{name}{sig}'")
        
        # 提取类并遍历类内方法
        elif inspect.isclass(member) and not name.startswith('__'):
            # 按示例将类名转为小写,若需保留原大小写则改为class_name = name
            class_name = name.lower()
            for method_name, method in inspect.getmembers(member):
                # 提取类内方法(排除双下划线开头的内置方法,保留单下划线的私有方法)
                if (inspect.isfunction(method) or inspect.ismethod(method)) and not method_name.startswith('__'):
                    sig = inspect.signature(method)
                    output.append(f"'{class_name}.{method_name}{sig}'")
    
    # 按要求格式拼接结果
    return ', '.join(output)

使用示例

假设file_1.py内容如下:

import file_2

def fo(x):
    pass

class A:
    def fun(y):
        pass
    
    def _bo(y):
        pass

调用函数:

print(get_functions_and_methods('file_1.py'))

输出结果:

'fo(x)', 'a.fun(y)', 'a._bo(y)'

关键细节说明

  • 模块加载:通过importlib.util直接加载指定路径的文件,无需将文件放入Python搜索路径,避免环境干扰。
  • 成员判断:用inspect模块的工具函数准确区分函数、类和方法,排除Python内置的特殊成员(如__init__、__name__)。
  • 签名生成:inspect.signature自动提取函数/方法的参数签名,保证输出格式与示例一致。
  • 类名处理:示例中要求类名小写,代码中通过name.lower()实现,若需保留原类名(如A.fun(y)),直接将class_name = name.lower()改为class_name = name即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 07:36:34