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

问题描述 投票:0回答:1

我有两个文件:

my_file.py
test.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
获取所有类。 现在我想获取此类的所有属性(变量/方法等...)

如何使用检查模块做到这一点?

python inspect
1个回答
0
投票

这是使用

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)]
© www.soinside.com 2019 - 2024. All rights reserved.