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

如何用inspect模块获取Python类的所有属性(变量/方法等)

解决方案

先修正原test.py中不需要的self参数(该函数并非类方法),再通过inspect模块扩展功能,实现获取类的所有自定义属性并区分类型的需求。

原文件代码

my_file.py

def heelo_friends():
    random_var = 56

class Attack:
    ss = 741
    def the_function():
        pass

修改后的test.py

import my_file as mf
import inspect 

def get_classes_with_attributes():
    classes_info = []
    # 遍历模块成员,筛选出所有类
    for name in dir(mf):
        obj = getattr(mf, name)
        if inspect.isclass(obj):
            class_attrs = {}
            # 获取当前类的所有成员
            for attr_name, attr_value in inspect.getmembers(obj):
                # 过滤内置特殊属性(以__开头和结尾的)
                if not (attr_name.startswith('__') and attr_name.endswith('__')):
                    # 判断属性类型
                    if inspect.isfunction(attr_value):
                        class_attrs[attr_name] = "方法"
                    else:
                        class_attrs[attr_name] = f"类变量,值为: {attr_value}"
            # 整理当前类的信息
            classes_info.append(f"类名: {name}")
            for attr, type_info in class_attrs.items():
                classes_info.append(f"  - {attr}: {type_info}")
            classes_info.append("")  # 添加空行分隔不同类
    return "\n".join(classes_info)

# 测试执行
if __name__ == "__main__":
    print(get_classes_with_attributes())

代码说明

  1. 筛选模块中的类:通过dir(mf)遍历模块成员,结合inspect.isclass判断是否为类对象。
  2. 获取类的属性:使用inspect.getmembers(obj)获取类的所有成员,返回属性名与属性值的元组列表。
  3. 过滤内置属性:排除以__包裹的内置特殊属性(如__dict__、__module__),只保留自定义内容。
  4. 区分属性类型:用inspect.isfunction识别类中的方法,其余归为类变量并显示对应值。

运行输出

执行test.py后会得到:

类名: Attack
  - ss: 类变量,值为: 741
  - the_function: 方法

内容的提问来源于stack exchange,提问作者Ninja-Flex6969

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 05:33:26