I'm in a model and I want to get an attribute of the model, but I have the attribute as a string.
It would be right to do this:
self.nombre
but I have this:
text = "nombre"
how do I access the attribute with what I have
I'm in a model and I want to get an attribute of the model, but I have the attribute as a string.
It would be right to do this:
self.nombre
but I have this:
text = "nombre"
how do I access the attribute with what I have
The getattr function, is one of the famous built-in functions of python, these help us mainly for things of instrospeción and metaprogramción.
The name of the function in Spanish can be translated as an attribute, which is quite descriptive of what it does.
This function receives two parameters an object, which will be an instance of some class and a string, which represents the name of the attribute
Specifically, this function will return the value of the attribute of a given object, if in any case we pass an attribute that does not exist in the object, an AttributeError type exception is thrown. We obtain the same result using the access point obj.attr
.
Useful cases of this function, is for example if we wanted to ask the user by screen what attribute he wants to obtain:
Example:
class Person(object):
def __init__(name, age):
self.name = name
self.age = age
person = Person('Jorge', 18)
attr = input('Que atributo desea recuperar')
print(getattr(person, attr)) #=> Nos devolvera el valor del atributo que el usuario escojio, o una excepción
You can find a little more information here: link