Bird
0
0

You want to add multiple custom attributes brand and year to an object car using a dictionary attrs = {"brand": "Toyota", "year": 2020}. Which code correctly adds these attributes?

hard📝 Application Q8 of 15
Python - Custom Exceptions
You want to add multiple custom attributes brand and year to an object car using a dictionary attrs = {"brand": "Toyota", "year": 2020}. Which code correctly adds these attributes?
Afor k, v in attrs.items(): setattr(car, k, v)
Bcar.attrs = attrs
Ccar[attrs.keys()] = attrs.values()
Dsetattr(car, attrs)
Step-by-Step Solution
Solution:
  1. Step 1: Understand how to add multiple attributes from a dictionary

    Use a loop to assign each key-value pair as an attribute and value.
  2. Step 2: Evaluate each option

    for k, v in attrs.items(): setattr(car, k, v) loops over dictionary items and uses setattr correctly. car.attrs = attrs assigns the whole dictionary as one attribute, not individual attributes. car[attrs.keys()] = attrs.values() uses invalid syntax. setattr(car, attrs) misuses setattr with one argument.
  3. Final Answer:

    for k, v in attrs.items(): setattr(car, k, v) -> Option A
  4. Quick Check:

    Loop with setattr adds multiple attributes [OK]
Quick Trick: Loop over dict and use setattr to add many attributes [OK]
Common Mistakes:
  • Assigning dict as one attribute instead of multiple
  • Using invalid syntax with brackets
  • Calling setattr with wrong number of arguments

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes