简体   繁体   中英

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

I'm trying to gather all the name attributes of my class' members:

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

I've tried both of these methods that I've seen here but the 1st is giving me names of all members. The second is giving the members themselves, but in a list, and I want to have a specific attribute. I tried something like

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

but that gives me

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

How can I achieve my goal here?

Just to show name is one of config 's attributes: dir(config) will result:

['_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']

You have a mistakes using vars() ; It returns a dict .

You can use the following to get all the names of all the vars of an object:

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

If you are interested in the class variables, then just call this method with the class instead of an instance:

names = get_var_names(Tree)

For example:

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

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

get_var_names(TestCase)

prints:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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