use str as variable name

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Thu Sep 4 03:47:07 EDT 2008


En Thu, 04 Sep 2008 04:25:37 -0300, Mathieu Prevot  
<mathieu.prevot at gmail.com> escribi�:

> I have a program that take a word as argument, and I would like to
> link this word to a class variable.
>
> eg.
> class foo():
>   width = 10
>   height = 20
>
> a=foo()
> arg='height'
> a.__argname__= new_value
>
> rather than :
>
> if arg == 'height':
>   a.height = new_value
> elif arg == 'width';
>   a.width = new_value

You're looking for "setattr":

setattr(a, arg, new_value)

http://docs.python.org/lib/built-in-funcs.html#l2h-66

>
> Can I do this with python ? How ?
>
> Thanks,
> Mathieu
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Gabriel Genellina




More information about the Python-list mailing list