简体   繁体   English

Python类动态属性访问

[英]Python Class dynamic attribute access

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. 但这在Python中不起作用。 How can I do this? 我怎样才能做到这一点?

Use setattr : 使用setattr

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

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

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

Use getattr for the reverse: 反向使用getattr

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? 您是否尝试过使用字典而不是课堂?

eval is for evaluation, use exec to 'execute' statements: eval用于评估,请使用exec '执行'语句:

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 . 由于您setattr名称设置属性,因此在Hop的答案中解释的setattr是更好的做法,并且比使用exec更安全。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM