Bird
0
0

How can you create a class attribute that holds a dictionary mapping names to ages, and update it when creating new instances?

hard📝 Application Q9 of 15
Python - Classes and Object Lifecycle
How can you create a class attribute that holds a dictionary mapping names to ages, and update it when creating new instances?
Aclass Person: ages = {} def __init__(self, name, age): Person.ages[name] = age
Bclass Person: ages = {} def __init__(self, name, age): self.ages = {name: age}
Cclass Person: def __init__(self, name, age): ages = {} ages[name] = age
Dclass Person: def __init__(self, name, age): self.ages = {} self.ages[name] = age
Step-by-Step Solution
Solution:
  1. Step 1: Define class attribute dictionary

    Define ages = {} inside class body to share among all instances.
  2. Step 2: Check each option

    class Person: ages = {} def __init__(self, name, age): Person.ages[name] = age correctly updates Person.ages. class Person: ages = {} def __init__(self, name, age): self.ages = {name: age} creates an instance attribute, others fail to share.
  3. Final Answer:

    class Person:\n ages = {}\n def __init__(self, name, age):\n Person.ages[name] = age -> Option A
  4. Quick Check:

    Update class dict attribute via ClassName.attribute inside methods [OK]
Quick Trick: Modify class dict attribute using ClassName.attribute inside __init__ [OK]
Common Mistakes:
  • Using self.ages to update class dict
  • Defining dict inside __init__
  • Not using class name to update dict

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes