Bird
0
0

You want to create a class Counter that counts how many times its method increment is called on each object separately. Which code correctly implements this behavior?

hard📝 Application Q15 of 15
Python - Methods and Behavior Definition
You want to create a class Counter that counts how many times its method increment is called on each object separately. Which code correctly implements this behavior?
Aclass Counter: def __init__(self): self.count = 0 def increment(self): self.count += 1 def get_count(self): return self.count
Bclass Counter: count = 0 def increment(self): Counter.count += 1 def get_count(self): return Counter.count
Cclass Counter: def __init__(self): self.count = 0 def increment(): self.count += 1 def get_count(self): return self.count
Dclass Counter: def __init__(self): self.count = 0 def increment(self): count += 1 def get_count(self): return self.count
Step-by-Step Solution
Solution:
  1. Step 1: Understand instance vs class variables

    Instance variables (self.count) ensure each object tracks its own count separately. Methods must accept self and update self.count.
  2. Step 2: Eliminate incorrect approaches

    Class variables are shared across all instances. Missing self parameter in methods causes TypeError. Updating a local variable doesn't affect the instance attribute.
  3. Final Answer:

    class Counter: def __init__(self): self.count = 0 def increment(self): self.count += 1 def get_count(self): return self.count -> Option A
  4. Quick Check:

    Instance variables + self = separate counts [OK]
Quick Trick: Use self.variable for per-object data, not class variables [OK]
Common Mistakes:
  • Using class variables for per-object data
  • Forgetting self in method parameters
  • Incrementing local variables instead of instance attributes

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes