I have a list with multiple objects that have multiple attributes. Through a method I intend to modify certain attributes of a certain object. I use this method **args
to be able to pass the attributes and values to modify, for example, (nombre='nuevo nombre', ID=123, direccion='Madrid)
and that I go through like a dictionary. But I'm not sure how to efficiently access the object's attribute to modify it.
This is the code:
def mod_objeto(self, nombre, **atrs):
''' Modifica los atributos de un objeto'''
# Obtengo la posición de un objeto dentro de una lista.
pos = self.busca_servicio(nombre)
# Copio el objeto en obj
obj = self.lista_servicios[pos]
for atr, val in atrs.items():
obj.atr = val # No funciona
# Actualizo el objeto de la lista.
self.lista_servicios[pos] = obj
Without going into assessing whether there is a better way to do what you propose, for which more information about your particular case would be needed, to be able to assign a value to an attribute using a string with its name to identify it, you can use the built-in
setattr
:Let's create a small simplified example based on your code:
As it happens when we assign via
self.attr = valor
, if the instance attributeattr
does not exist it is created. If you want to avoid this situation, by throwing an exception if it occurs, you can simply take advantage offor
to do the check usinghasattr
.It would also be possible to update directly
__dict__
:but as a general rule it is not recommended, among other things this ignores properties and descriptors in general. Obviously it doesn't work in the use case either
slots
.