9

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'
1

1 Answer 1

21

Use getattr:

var = 'classname'
getattr(cls, var)
Sign up to request clarification or add additional context in comments.

4 Comments

b="a."+var b 'a.classname' eval(b) u'CIM_RegisteredProfile'
@brike, try to avoid eval whenever possible. Read the answers on this SO question or google "eval is evil".
getattr is the Pythonic answer.
I'm tempted to flag that suggestion of eval as an alternative as 'offensive'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.