Python Class dynamic attribute access

喜你入骨 提交于 2019-11-29 16:30:14

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?

BigOther

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!