Python - 如何使用inspect获取函数/类的所有属性

0 投票
1 回答
38 浏览
提问于 2025-04-12 22:52

我有两个文件:my_file.pytest.py

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 
import sys 
    
    def get_classes(self) -> list:
        classes = []
        for x in dir(mf):
            obj = getattr(mf,x)
            if inspect.isclass(obj):
                classes.append(x)
                
        return f"All classes : {classes}"
        # All classes : ['Attack']

这个文件会从 my_file.py 中获取所有的类。

现在我想获取这些类中的所有属性(比如变量、方法等等)。

我该如何使用 inspect 模块来实现这个呢?

1 个回答

1

这里有一个使用 inspect.getmembers 的解决方案:

# 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 
import sys 

def get_classes(self) -> list:
    classes = []
    for x in dir(mf):
        obj = getattr(mf,x)
        if inspect.isclass(obj):
            classes.append(x)

    return f"All classes : {classes}"

attack = mf.Attack()
attributes = inspect.getmembers(attack, lambda x:not(inspect.isroutine(x)))
print("Attributes:", attributes)

输出结果:

Attributes: [('__class__', <class 'my_file.Attack'>), ('__delattr__', <method-wrapper '__delattr__' of Attack object at 0x102bd8fd0>), ('__dict__', {}), ('__doc__', None), ('__eq__', <method-wrapper '__eq__' of Attack object at 0x102bd8fd0>), ('__ge__', <method-wrapper '__ge__' of Attack object at 0x102bd8fd0>), ('__getattribute__', <method-wrapper '__getattribute__' of Attack object at 0x102bd8fd0>), ('__gt__', <method-wrapper '__gt__' of Attack object at 0x102bd8fd0>), ('__hash__', <method-wrapper '__hash__' of Attack object at 0x102bd8fd0>), ('__init__', <method-wrapper '__init__' of Attack object at 0x102bd8fd0>), ('__le__', <method-wrapper '__le__' of Attack object at 0x102bd8fd0>), ('__lt__', <method-wrapper '__lt__' of Attack object at 0x102bd8fd0>), ('__module__', 'my_file'), ('__ne__', <method-wrapper '__ne__' of Attack object at 0x102bd8fd0>), ('__repr__', <method-wrapper '__repr__' of Attack object at 0x102bd8fd0>), ('__setattr__', <method-wrapper '__setattr__' of Attack object at 0x102bd8fd0>), ('__str__', <method-wrapper '__str__' of Attack object at 0x102bd8fd0>), ('__weakref__', None), ('ss', 741)]

撰写回答