如何获取Python类中的函数名称?以CustomETL类为例
获取Python类中函数名称的实现方法
以下两种方法可以帮你提取CustomETL类中的函数名称,并格式化为你需要的逗号分隔字符串:
方法一:使用inspect模块(推荐)
inspect模块是Python专门用于检查代码对象的工具,能精准筛选出类中的函数:
import inspect class CustomETL: def func2(df): counts.save() def extract_and_transform(): colunas = ['nome', ' idade', ' cpf', ' ativo', ' nascimento', ' estado'] df = colunas.to_pandas().save().write() return df # 筛选类中的函数成员 function_names = [name for name, member in inspect.getmembers(CustomETL) if inspect.isfunction(member)] # 转换为逗号分隔的字符串 output = ', '.join(function_names) print(output) # 输出:func2, extract_and_transform
方法二:使用dir()和callable()
如果不想引入额外模块,可以通过dir()列出类的所有属性,再筛选出非特殊方法的可调用对象:
class CustomETL: def func2(df): counts.save() def extract_and_transform(): colunas = ['nome', ' idade', ' cpf', ' ativo', ' nascimento', ' estado'] df = colunas.to_pandas().save().write() return df # 过滤掉特殊方法(以__开头),并检查是否为可调用函数 function_names = [attr for attr in dir(CustomETL) if not attr.startswith('__') and callable(getattr(CustomETL, attr))] output = ', '.join(function_names) print(output) # 输出:func2, extract_and_transform
说明
两种方法都会排除Python类自带的特殊方法(如__init__、__str__等),只返回你自定义的函数名称,最终输出格式完全符合你的需求。
内容的提问来源于stack exchange,提问作者Jefferson
相关产品推荐
相关产品推荐

