Bird
0
0

You want to write a context manager that counts how many times the block inside with runs and prints the count after all uses. Which approach correctly implements this behavior?

hard📝 Application Q15 of 15
Python - Context Managers
You want to write a context manager that counts how many times the block inside with runs and prints the count after all uses. Which approach correctly implements this behavior?
AUse a class with instance variable counting and print in __enter__.
BUse a function with yield and print count after the yield.
CUse a class with a class variable to count entries and print in __exit__.
DUse a function that returns a list of counts each time it's called.
Step-by-Step Solution
Solution:
  1. Step 1: Understand the requirement to count multiple uses

    Counting how many times the block runs requires storing count across instances, so a class variable is needed.
  2. Step 2: Identify where to print the count

    Printing after all uses means printing in __exit__ after each block ends. Using a class variable allows accumulation.
  3. Step 3: Evaluate options

    Use a class with a class variable to count entries and print in __exit__. uses a class variable and prints in __exit__, matching the requirement. Use a function with yield and print count after the yield. is a generator but doesn't accumulate count across uses. Use a class with instance variable counting and print in __enter__. uses instance variable, which resets each time. Use a function that returns a list of counts each time it's called. is unrelated to context managers.
  4. Final Answer:

    Use a class with a class variable to count entries and print in __exit__. -> Option C
  5. Quick Check:

    Class variable + __exit__ print = A [OK]
Quick Trick: Use class variable to track count across with blocks [OK]
Common Mistakes:
  • Using instance variables that reset each time
  • Printing count too early in __enter__
  • Confusing generator functions with context managers

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes