How do I list all the properties of an object?

-1

I wanted to get only the properties of an object, and pass the value of each of these properties as an argument to a function.

    
asked by anonymous 13.11.2017 / 15:08

1 answer

2

You can iterate over all components of your object's class and search for those that are of type property . To get all components, we can use the dir function, which returns both class attributes, instance attributes, methods, and properties. To search only the properties, just filter this list by type. It is worth remembering that the list of components must be elaborated from the class of the object and not of the object itself, otherwise the return of the function type of the property would give the type of the value of the property and not of the property itself. / p>

As an example, we imagine the following class:

class Foo:

    atributo_de_classe = 1

    def __init__(self):
        self.atributo_de_instancia = 2

    @property
    def propriedade(self):
        return 3

    def metodo(self):
        return 4

I defined both the class attribute and the instance, method, and property attribute, each with its own name for easy identification. If you want to get only the properties, the only value returned should be propriedade .

We will define the function that will take the name of all the properties of an object:

def get_properties_names(obj):
     classname = obj.__class__
     components = dir(classname)
     properties = filter(lambda attr: type(getattr(classname, attr)) is property, components)
     return properties

So, if we create an instance of the above class and call this function for it, we will have:

foo = Foo()
properties = get_properties_names(foo)
print(properties)  # ['propriedade']

Returning only the name of the properties of the class. To get the value of each property, we can use the getattr function with the object:

foo = Foo()
properties = [getattr(foo, property) for property in get_properties_names(foo)]
print(properties)  # [3]

Returning the list of values of object properties. So you can use list deconstruction to pass, for example, per parameter to a function:

another_function(*properties)
    
13.11.2017 / 17:03