Python:按变量访问类属性

时间:2012-01-17 03:36:38

标签: python variables

在python中如何以cls.variable格式访问实例的属性?

(在ruby中,它可以是格式cls。#{variable})

>>>cls.classname
u'CIM_RegisteredProfile'

>>>var='classname'

>>>cls.var
Traceback (most recent call last):
  File "<console>", line 0, in <module>
AttributeError: 'CIMClass' object has no attribute 'var'

1 个答案:

答案 0 :(得分:6)

使用getattr

var = 'classname'
getattr(cls, var)