Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q5 of 15
Python - Custom Exceptions
What will be the output of this code?
class Person:
    pass

p = Person()
setattr(p, 'name', 'Alice')
print(p.name)
Aname
BAlice
CAttributeError
DNone
Step-by-Step Solution
Solution:
  1. Step 1: Understand setattr function usage

    setattr(object, attribute_name, value) adds or updates an attribute on the object.
  2. Step 2: Trace the code

    Attribute name is set to "Alice" on instance p. Printing p.name outputs "Alice".
  3. Final Answer:

    Alice -> Option B
  4. Quick Check:

    setattr sets attribute value correctly = Alice [OK]
Quick Trick: Use setattr(obj, 'attr', value) to add attributes dynamically [OK]
Common Mistakes:
  • Mixing order of setattr arguments
  • Expecting attribute name printed instead of value
  • Forgetting to use quotes around attribute name

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes