3

I want to access a class attribute by a string with its name.

Something like:

class a:
    b=[]

c='b'
eval('a.'+c+'=1')

But that doesn't work in Python. How can I do this?

Vasfed
  • 18,013
  • 10
  • 47
  • 53

2 Answers2

7

Use setattr:

In [1]: class a:
   ...:     b = []
   ...:     

In [2]: setattr(a, 'b', 1)

In [3]: a.b
Out[3]: 1

Use getattr for the reverse:

In [4]: getattr(a, 'b')
Out[4]: 1

In [5]: getattr(a, 'x', 'default')
Out[5]: 'default'

I very much suspect, though, that there is a better way to achieve whatever your goal is. Have you tried using a dictionary instead of a class?

2

eval is for evaluation, use exec to 'execute' statements:

exec('a.'+c+'=1')

Yet, consider the risk of using both. And you can check out this answer for the difference between expressions and statements.

Since you are looking to set attribute by name, setattr explained in hop's answer is a better practice, and safer than using exec.

Community
  • 1
  • 1
Assem
  • 11,574
  • 5
  • 59
  • 97
  • Wow, I didn't expect such a quit answer. Thanks a lot. – jeansergecardinal Jan 16 '16 at 20:08
  • If you think you need `eval` or `exec`, you are wrong. –  Jan 16 '16 at 20:14
  • 1
    Note that using eval/exec is dangerous as this probably can open a code execution vulnerability – Vasfed Jan 16 '16 at 20:16
  • I want to save the widget values of a GUI in a file. But when I retreive the file I get attribute name and values to set. – jeansergecardinal Jan 16 '16 at 20:31
  • @GeneralExeption the best way to update an attribute by name is not using eval or exect because they are too risky. Use `setattr` : check the other answer :http://stackoverflow.com/a/34831594/1327005 – Assem Jan 16 '16 at 20:34