|  | use str as variable name |  | |
| | | Mathieu Prevot |  |
| Posted: Thu Sep 04, 2008 5:25 am Post subject: use str as variable name |  |
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
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 |
| |
| | | Chris Rebert |  |
| Posted: Thu Sep 04, 2008 5:36 am Post subject: Re: use str as variable name |  |
On Thu, Sep 4, 2008 at 12:25 AM, Mathieu Prevot <mathieu.prevot@gmail.com> wrote:
| Quote: | 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):
| Quote: | 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
| Quote: | 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 -- LINK
|
-- Follow the path of the Iguana... LINK |
| |
| | | Fredrik Lundh |  |
| Posted: Thu Sep 04, 2008 5:36 am Post subject: Re: use str as variable name |  |
Mathieu Prevot wrote:
| Quote: | 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
Can I do this with python ? How ?
|
assuming you mean "instance variable" ("a" is an instance of the class "foo"), you can use setattr:
a = foo() arg = 'height' setattr(a, arg, new_value)
</F> |
| |
| | | Gabriel Genellina |  |
| Posted: Thu Sep 04, 2008 5:47 am Post subject: Re: use str as variable name |  |
En Thu, 04 Sep 2008 04:25:37 -0300, Mathieu Prevot <mathieu.prevot@gmail.com> escribi�:
| Quote: | 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)
LINK
| Quote: | Can I do this with python ? How ?
Thanks, Mathieu -- LINK
|
-- Gabriel Genellina |
| |
|
|