Bird
0
0

Which of the following statements correctly adds a custom attribute age with value 5 to an instance dog of a class Animal?

easy📝 Conceptual Q2 of 15
Python - Custom Exceptions
Which of the following statements correctly adds a custom attribute age with value 5 to an instance dog of a class Animal?
Adog["age"] = 5
Bdog.age = 5
Csetattr(dog, 5, "age")
Ddog.add("age", 5)
Step-by-Step Solution
Solution:
  1. Step 1: Recall how to add attributes to class instances

    Instances can have attributes added by assigning with dot notation: instance.attribute = value.
  2. Step 2: Evaluate each option

    dog.age = 5 correctly assigns age attribute. dog["age"] = 5 uses dictionary syntax which is invalid for objects. setattr(dog, 5, "age") misuses setattr parameters order. dog.add("age", 5) calls a non-existent method.
  3. Final Answer:

    dog.age = 5 -> Option B
  4. Quick Check:

    Instance attribute assignment = dog.age = 5 [OK]
Quick Trick: Use dot notation to add attributes to instances [OK]
Common Mistakes:
  • Using dictionary syntax on objects
  • Incorrect order of setattr arguments
  • Calling undefined methods on objects

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes