Using eval, or something like it...

r0g aioe.org at technicalbloke.com
Thu Nov 20 01:59:45 EST 2008


John Machin wrote:
> 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.


The former i.e. the variables of an instance of a class. Thanks :-)

Roger.



More information about the Python-list mailing list