Python Class dynamic attribute access

眉间皱痕 提交于 2019-12-18 09:29:20

问题


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.



来源:https://stackoverflow.com/questions/34831505/python-class-dynamic-attribute-access

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