setattr() — Python Technical Interview Questions & Answers

setattr()

setattr()

  • setattr() is built into Python. You do not import it. Freshers only need one honest call and the printed result — not a long definition.
  • setattr() — output: Asha. setattr writes an attribute by name.
  • Wrong type often raises TypeError. Empty values matter for bool/all/any. Don’t mix setattr up with a similar name (sorted vs sort, int vs float).

Technical Interview Tip: Call setattr() once and say what prints.

Code Examples for setattr()

Example

# setattr()
class S: pass
s = S()
setattr(s, "name", "Asha")
print(s.name)

setattr() — output: Asha. setattr writes an attribute by name.

How to Explain setattr() to an Interviewer

Explain setattr() as if you are teaching a junior — definition, then one tiny script.

setattr() is built-in — no import. One call + exact output.

What does the example print, and why?

setattr() — output: Asha

What mistake do freshers make with setattr()?

Wrong type → TypeError.