use str as variable name

Nick Craig-Wood nick at craig-wood.com
Thu Sep 4 10:35:52 CEST 2008


Mathieu Prevot <mathieu.prevot at gmail.com> wrote:
>  Hi,
> 
>  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

Not quite sure what the above is supposed to achieve

>  rather than :
> 
>  if arg == 'height':
>    a.height = new_value
>  elif arg == 'width';
>    a.width = new_value
> 
>  Can I do this with python ? How ?

setattr(a, arg, new_value)

See: http://docs.python.org/lib/built-in-funcs.html


-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list