Search code examples
pythonstringoopobjectevaluate

Evaluate string to an object and changing / assigning value


Is there a way of writing this piece of code other than using exec to evaluate code? Is there something I'm missing from the manual?

Class Object():

    def __init__(self):
        self.a = 200
        self.y = 400

list = [
'o.x',
'o.y',
'o.z'
]

o = Object()

for item in list:
    exec(item + ' = 1000')

What I really wanted to in my dream was this:

for item in list:
    item = 1000

But for obvious reasons 'exec' is what I went with since no evaluation would ever take place.


Solution

  • Use setattr() to set the value of the instance attribute by string:

    >>> class A():
    ...     def __init__(self):
    ...         self.a = 200
    ...         self.y = 400
    ... 
    >>> a = A()
    >>> l = ['x', 'y', 'z']
    >>> for item in l:
    ...     setattr(a, item, 1000)
    ... 
    >>> a.x
    1000
    >>> a.y
    1000
    >>> a.z
    1000