7

in python how to access instance's attribute as cls.variable format?

(in ruby, it can be in format 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'
brike
  • 313
  • 4
  • 10
  • 1
    possible duplicate of [Python: Accessing an attribute using a variable](http://stackoverflow.com/questions/2157035/python-accessing-an-attribute-using-a-variable) – S.Lott Jan 17 '12 at 03:49

1 Answers1

18

Use getattr:

var = 'classname'
getattr(cls, var)
Rob Wouters
  • 15,797
  • 3
  • 42
  • 36
  • b="a."+var b 'a.classname' eval(b) u'CIM_RegisteredProfile' – brike Jan 17 '12 at 03:44
  • 2
    @brike, try to avoid `eval` whenever possible. Read the answers on [this SO question](http://stackoverflow.com/questions/86513/why-is-using-javascript-eval-function-a-bad-idea) or google "eval is evil". – Rob Wouters Jan 17 '12 at 03:49
  • `getattr` is the Pythonic answer. – MRAB Jan 17 '12 at 03:49
  • 2
    I'm tempted to flag that suggestion of eval as an alternative as 'offensive' – wim Jan 17 '12 at 03:54