Bird
0
0

You want to keep track of how many objects of class Student are created using a class attribute count. Which code correctly updates count each time a new Student is made?

hard📝 Application Q15 of 15
Python - Classes and Object Lifecycle
You want to keep track of how many objects of class Student are created using a class attribute count. Which code correctly updates count each time a new Student is made?
Aclass Student: count = 0 def __init__(self): self.count += 1
Bclass Student: count = 0 def __init__(self): Student.count += 1
Cclass Student: def __init__(self): count = 0 count += 1
Dclass Student: count = 0 def __init__(self): count += 1
Step-by-Step Solution
Solution:
  1. Step 1: Identify class attribute usage

    count is a class attribute, so it should be accessed via the class name inside methods.
  2. Step 2: Check each option for correct increment

    class Student: count = 0 def __init__(self): Student.count += 1 uses Student.count += 1, correctly updating the class attribute. class Student: count = 0 def __init__(self): self.count += 1 tries to increment self.count, which creates an instance attribute instead. Options C and D have syntax or scope errors.
  3. Final Answer:

    class Student: count = 0 def __init__(self): Student.count += 1 -> Option B
  4. Quick Check:

    Update class attribute via ClassName.attribute [OK]
Quick Trick: Use ClassName.attribute to update class attributes inside methods [OK]
Common Mistakes:
  • Using self.attribute to update class attribute
  • Defining count inside __init__ instead of class
  • Forgetting to use class name to access class attribute

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes