Bird
0
0

Find the mistake in this code that tries to add a custom attribute weight to obj:

medium📝 Debug Q7 of 15
Python - Custom Exceptions
Find the mistake in this code that tries to add a custom attribute weight to obj:
class Item:
    pass

obj = Item()
setattr(obj, weight, 50)
print(obj.weight)
Aweight should be a string in setattr
Bobj.weight is not defined
Csetattr requires only two arguments
Dprint statement missing parentheses
Step-by-Step Solution
Solution:
  1. Step 1: Check setattr function parameters

    setattr requires the attribute name as a string.
  2. Step 2: Identify the error

    The code passes weight without quotes, so Python treats it as a variable which is undefined, causing a NameError.
  3. Final Answer:

    weight should be a string in setattr -> Option A
  4. Quick Check:

    Attribute name in setattr must be string [OK]
Quick Trick: Always quote attribute names in setattr [OK]
Common Mistakes:
  • Passing attribute name without quotes
  • Confusing variable and string for attribute name
  • Miscounting setattr arguments

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes