如何列出类中所有成员的特定属性(Python3.5.3)

2024-04-25 11:38:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图收集类成员的所有name属性:

from anytree import Node, RenderTree
class Tree:
    config = Node('configure')
    # other class variables...

    def get_all_members(self):
    # tried this option first
    members = [attr for attr in dir(self) if not callable(getattr(self, attr)) and not attr.startswith("__")]
    # and then deleted first option and tried this option
    members = vars(Tree)
    return members

我已经尝试过这两种我见过的方法here,但第一种方法是给出所有成员的名称。第二个是给成员自己,但是在一个列表中,我想有一个特定的属性。我试过

^{pr2}$

但这给了我

members = [name for name in vars(Tree).name]

我如何在这里实现我的目标?在

为了显示nameconfig的属性之一:dir(config)将得到:

['_NodeMixin__attach', '_NodeMixin__check_loop', '_NodeMixin__detach', 'class', 'delattr', 'dict', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'gt', 'hash', 'init', 'le', 'lt', 'module', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'sizeof', 'str', 'subclasshook', 'weakref', '_children', '_name', '_parent', '_path', '_post_attach', '_post_detach', '_pre_attach', '_pre_detach', 'anchestors', 'children', 'depth', 'descendants', 'height', 'is_leaf', 'is_root', 'name', 'parent', 'path', 'root', 'separator', 'siblings']


Tags: andnameselfconfigtree属性dir成员
1条回答
网友
1楼 · 发布于 2024-04-25 11:38:13

使用vars()时出错;它返回一个dict。在

可以使用以下命令获取对象所有变量的所有名称:

def get_var_names(obj):
    return {v: o.name for v,o in vars(obj).items() if hasattr(o, 'name')}

如果您对类变量感兴趣,那么只需使用类而不是实例调用此方法:

^{pr2}$

例如:

^{3}$

印刷品:

{'a': 'a', 'b': 'b'}

相关问题 更多 >

    热门问题