python class variable update based on dictionary -


how can update class variable dictionary? i've came dirty hack, i'm looking (if there is) more neat.

let's want class c parameters set based on given dictionary. result, c should have

class c:     def setvar(self, var):         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 

this setattr for:

def setvar(self, var):     key, value in var.items():         setattr(self, key, value) 

more generally, time find looking @ eval or exec, reflective function setattr first, , you'll find one.


if know class using simple __dict__ instance attributes, , of these instance attributes (that's standard case—and if don't know of means, it's true code), can quick&dirty hack:

def setvar(self, var):     self.__dict__.update(var) 

however, setattr works in case makes sense, , fails appropriately in cases doesn't, , of course says it's doing—it's setting attribute on self named key value, attribute stored—makes cleaner.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -