Python Class dynamic attribute access

2019-03-01 17:28发布

问题:

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?

回答1:

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.