use str as variable name

Chris Rebert cvrebert at gmail.com
Thu Sep 4 03:36:13 EDT 2008


On Thu, Sep 4, 2008 at 12:25 AM, 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():

You should subclass 'object', so that should be:
    class Foo(object):

>  width = 10
>  height = 20
>
> a=foo()
> arg='height'
> a.__argname__= new_value

You're looking for the setattr() built-in function. In this exact case:
    setattr(a, arg, new_value)

This is probably covered in the Python tutorial, please read it.

Regards,
Chris

>
> rather than :
>
> if arg == 'height':
>  a.height = new_value
> elif arg == 'width';
>  a.width = new_value
>
> Can I do this with python ? How ?
>
> Thanks,
> Mathieu
> --
> http://mail.python.org/mailman/listinfo/python-list
>

-- 
Follow the path of the Iguana...
http://rebertia.com



More information about the Python-list mailing list