我试图收集类成员的所有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]
我如何在这里实现我的目标?在
为了显示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()
时出错;它返回一个dict
。在可以使用以下命令获取对象所有变量的所有名称:
如果您对类变量感兴趣,那么只需使用类而不是实例调用此方法:
^{pr2}$例如:
^{3}$印刷品:
相关问题 更多 >
编程相关推荐