I would like to update the attributes of a class dynamically, but it seems that the combination of setattr and getattr does not work as I would like to use it.
Here is my main class:
class Container(object):
def __init__(self):
pass
container = Container()
attributes = ['a', 'b', 'c', 'd']
values = [[1, 2, 3, 4, 5], [True, False], ['red', 'blue', 'green'], [0, 1, -1, -5, 99]]
Please note that for the purpose of that example I explicitly constructed the list of attributes and their respective values. However, in the real application of this code, I do not know anything in advance. Neither their numbers, name, or values. This calls for the need to do that dynamically.
Here is the rest of the code:
for key, value in zip(attributes, values):
setattr(container, key, [])
for val in value:
setattr(container, key, getattr(container, key).append(val))
this part does not work when I run the code. I could save the getattr part in a tmp variable and then call the append method for the list before calling the setattr, but I would like to condense it if possible.
Anyone could explain me why this does not work? What alternative(s) do I have?
Thanks for your help