Bird
Raised Fist0

Identify the error in the following code that tries to add a custom attribute speed to object car:

medium📝 Debug Q6 of Q15
Python - Custom Exceptions
Identify the error in the following code that tries to add a custom attribute speed to object car:
class Vehicle:
    pass

car = Vehicle()
car["speed"] = 100
print(car.speed)
AUsing dictionary syntax on object causes TypeError
BMissing quotes around attribute name
CAttribute speed is not defined
Dprint statement syntax error
Step-by-Step Solution
Solution:
  1. Step 1: Understand attribute assignment vs dictionary syntax

    Objects do not support item assignment like dictionaries unless __setitem__ is defined.
  2. Step 2: Analyze the code error

    Line car["speed"] = 100 tries to assign using dictionary syntax, causing a TypeError. print(car.speed) will fail because speed attribute was never set.
  3. Final Answer:

    Using dictionary syntax on object causes TypeError -> Option A
  4. Quick Check:

    Objects need dot notation, not brackets = TypeError [OK]
Quick Trick: Use dot notation, not brackets, to add attributes [OK]
Common Mistakes:
MISTAKES
  • Using brackets on objects without __setitem__
  • Expecting attribute to exist after wrong assignment
  • Confusing dictionary and object syntax

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes