Using eval, or something like it...

John Machin sjmachin at lexicon.net
Wed Nov 19 20:26:15 EST 2008


On Nov 20, 11:44 am, r0g <aioe.... at technicalbloke.com> wrote:
> Hi There,
>
> I know you can use eval to dynamically generate the name of a function
> you may want to call. Can it (or some equivalent method) also be used to
> do the same thing for the variables of a class e.g.
>
> class Foo():
>   bar = 1
>   gum = 2
>
> mylist = ['bar','gum']
>
> a = Foo()
> for each in mylist:
>   a.eval(each) = 999
>
> If so, what is the proper syntax/method for this.

You mention "variables of a class" but you then proceed to poke at an
instance of the class. They are two different things. Which do you
mean?

In any case, use the built-in function setattr to set attribute values
for an object or for a class.

setattr(a, 'bar', 999) is equivalent to a.bar = 999
setattr(Foo, 'bar', 456) is equivalent to Foo.bar = 456

Check out setattr (and getattr) in the docs.



More information about the Python-list mailing list