Search code examples
python-3.xobjectattributes

How to create an isolated list of attributes for a python object?


I have a python object called my_obj that has many attributes called attr1, attr2, attr3, .... represented as strings.

I would like to create a list of these attributes in the following pattern:

attr_list = [my_obj.attr1, my_obj.attr2, my_obj.attr3]

where each element of the list is an object rather than a string using a for loop in which elements are added one at a time.

I don't know how to convert strings into object before appending them to the list consecutively.

Your help is greatly appreciated.


Solution

  • There is a built-in function that does what you need, off-the-shelf, in Python 3: getattr

    Official doc here

    Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute.

    We could use getattr this way to tackle your problem:

    attr_names = ["attr1", "attr2", "attr3"]
    attr_list = []
    
    for name in attr_names:
        attr = getattr(my_obj, name)
        attr_list.append(attr)