繁体   English   中英

如何列出我班上所有成员的特定属性(Python 3.5.3)

[英]How to list specific attribute of all members in my class (Python 3.5.3)

我正在尝试收集班级成员的所有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

我已经尝试过在这里看到的这两种方法,但是第一种是给我所有成员的名字。 第二个是给成员自己,但是在列表中,我想拥有一个特定的属性。 我尝试了类似的东西

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

但这给了我

成员= [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','儿童”,“深度”,“后裔”,“身高”,“ is_leaf”,“ is_root”, “ name” ,“ parent”,“ path”,“ root”,“ separator”,“兄弟姐妹”]

您使用vars()有一个错误; 它返回一个dict

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

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

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

names = get_var_names(Tree)

例如:

class Named:
    def __init__(self, name):
        self.name = name

class TestCase:
    a = Named("a")
    b = Named("b")

get_var_names(TestCase)

印刷品:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM