Python Class dynamic attribute access -


i want access class attribute string name.

something like:

class a:     b=[]  c='b' eval('a.'+c+'=1') 

but doesn't work in python. how can this?

use setattr:

in [1]: class a:    ...:     b = []    ...:       in [2]: setattr(a, 'b', 1)  in [3]: a.b out[3]: 1 

use getattr reverse:

in [4]: getattr(a, 'b') out[4]: 1  in [5]: getattr(a, 'x', 'default') out[5]: 'default' 

i suspect, though, there better way achieve whatever goal is. have tried using dictionary instead of class?


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -