Converting string to argument

Heather Coppersmith me at privacy.net
Fri Jul 2 14:08:59 CEST 2004


On Thu, 1 Jul 2004 18:07:16 -0700,
"Laughlin, Joseph V" <Joseph.V.Laughlin at boeing.com> wrote:

> class Foo:
> 	x = "blah"
> 	y = "blah some more"

> foo = Foo()
> x_string = "x"
> y_string = "y"

> # I want something like this to work:
> print foo.x_string
> print foo.y_string
> # The above should print out "blah" and "blah some more"
> # Any ideas?
> # Let me know if I need to clarify anything.

The usual comp.lang.python answer is "why do you want to do this?"

In most cases, wanting to do this is a symptom of something else
being sub-optimal.  Perhaps it's as simple as putting x and y into
a dictionary instead of creating them as class attributes:

    foo = { }
    foo[ "x" ] = "blah"
    foo[ "y" ] = "blah some more"

    x_string = "x"
    y_string = "y"

    print foo[ x_string ]
    print foo[ y_string ]

Regards,
Heather

-- 
Heather Coppersmith
That's not right; that's not even wrong. -- Wolfgang Pauli



More information about the Python-list mailing list