getattr() — Python Technical Interview Questions & Answers
getattr()
getattr()
- getattr() is built into Python. You do not import it. Freshers only need one honest call and the printed result — not a long definition.
- getattr() — output: Asha. getattr reads an attribute by name.
- Wrong type often raises TypeError. Empty values matter for bool/all/any. Don’t mix getattr up with a similar name (sorted vs sort, int vs float).
Technical Interview Tip: Call getattr() once and say what prints.
Code Examples for getattr()
Example
# getattr()
class S:
name = "Asha"
print(getattr(S(), "name"))
getattr() — output: Asha. getattr reads an attribute by name.
How to Explain getattr() to an Interviewer
Explain getattr() as if you are teaching a junior — definition, then one tiny script.
getattr() is built-in — no import. One call + exact output.
What does the example print, and why?
getattr() — output: Asha
What mistake do freshers make with getattr()?
Wrong type → TypeError.