python class variable update based on dictionary
class, dictionary, python, variables
Solution
This is exactly what `setattr` is for:
def setVar(self, var):
for key, value in var.items():
setattr(self, key, value)
More generally, almost any time you find yourself looking at `eval` or `exec`, look for a reflective function like `setattr` first, and you'll almost always find one.
If you know your class is using a simple `__dict__` for instance attributes, and all of these are instance attributes (that's the standard case—and if you don't know what all of that means, it's true for your code), you can do this quick&dirty hack:
def setVar(self, var):
self.__dict__.update(var)
However, `setattr` works in any case that makes sense, and fails appropriately in most cases that doesn't, and of course it says exactly what it's doing—it's setting an attribute on `self` named `key` to `value`, however that attribute is stored—makes it much cleaner.
Problem
How can I update class variable from dictionary? I've came up with a dirty hack, but I'm looking (if there is) for something more neat. Let's say I want a class C which parameters will be set based on given dictionary. As a result, c should have ``` class C: def setVar(self, var): for key in var.keys(): exec('self.{} = {}'.format(key, var[key])) D = {'a':1, 'b':2, 'c':3} c = C() c.setVar(D) # c.a = 1 # c.b = 2 # c.c = 3 ```