【问题标题】:How to list specific attribute of all members in my class (Python 3.5.3)如何列出我班级中所有成员的特定属性(Python 3.5.3)
【发布时间】:2017-05-16 14:52:55
【问题描述】:

我正在尝试收集班级成员的所有 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 看到的这两种方法,但第一种方法是给我所有成员的名字。第二个是给成员自己,但在一个列表中,我想有一个特定的属性。我尝试了类似的东西

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

但这给了我

members = [vars(Tree).name 中名称的名称]

我怎样才能在这里实现我的目标?

仅显示name 是config 的属性之一: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']

【问题讨论】:

  • 代码用vars(Tree) 覆盖members 列表...
  • @falsetru 我知道,我只是想展示我使用的两种方法。我显然分别使用了每个:) 我编辑了我的问题,因为不清楚

标签: python list python-3.x attributes


【解决方案1】:

您使用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'}

【讨论】:

  • 看来我还是卡住了...我想要成员本身,这样我就可以调用它的一些其他方法,但我只剩下它的名字了。这可以通过返回对成员本身的引用来完成吗?
  • 您可以将v: o.name 更改为v: (o.name, o)。现在第一个元素是名称,第二个是实际对象。
猜你喜欢
  • 1970-01-01
  • 2020-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-17
  • 1970-01-01
  • 1970-01-01
  • 2020-12-26
相关资源
最近更新 更多