python - Evaluate string to an object and changing / assigning value -
is there way of writing piece of code other using exec evaluate code? there i'm missing manual?
class object(): def __init__(self): self.a = 200 self.y = 400 list = [ 'o.x', 'o.y', 'o.z' ] o = object() item in list: exec(item + ' = 1000')
what wanted in dream this:
for item in list: item = 1000
but obvious reasons 'exec' went since no evaluation ever take place.
use setattr() set value of instance attribute string:
>>> class a(): ... def __init__(self): ... self.a = 200 ... self.y = 400 ... >>> = a() >>> l = ['x', 'y', 'z'] >>> item in l: ... setattr(a, item, 1000) ... >>> a.x 1000 >>> a.y 1000 >>> a.z 1000
Comments
Post a Comment