How do I list all the properties of an object?

Asked

Viewed 356 times

-1

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

  • 1

    Only properties? Or attributes and methods as well? Can you explain better what you want to do?

  • the best there would be put rum exmpo than you want: put a small class with the type of data you want, as Voce creates an instance of that class, and the call you would like to make.

1 answer

2

You can iterate over all the class components of your object and search for those that are of type property. To get all the components, we can use the function dir, which will return 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 drawn up from the class of the object and not from the object itself, because otherwise the return of the function type property would give the type of property value and not the property itself.

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

Define both class attribute, instance attribute, method and property, each with its own name to facilitate identification. If only the properties are desired, the only value returned should be propriedade.

We will thus define the function that will take the name of all 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 one to function to it, we will have:

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

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

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

Returning the value list of object properties. Thus, you can use list deconstruction to pass, for example, by parameter to a function:

another_function(*properties)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.