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.
Regards,
Roger.
解决方案DON''T USE eval!
On Thu, Nov 20, 2008 at 10:44 AM, r0g
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.
Regards,
Roger.
--
http://mail.python.org/mailman/listinfo/python-list
--
--
-- "Problems are solved by method"
On Nov 19, 7:44*pm, r0g
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.
for each in mylist:
setattr(a, each, 999)
HTH,
George
On Nov 20, 11:44*am, r0g
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.