Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q4 of 15
Python - Context Managers
What will be the output of this code?
class Manager:
    def __enter__(self):
        print('Start')
        return 'Resource'
    def __exit__(self, exc_type, exc_val, exc_tb):
        print('End')

with Manager() as m:
    print(m)
AEnd Start Resource
BResource Start End
CStart Resource End
DStart End Resource
Step-by-Step Solution
Solution:
  1. Step 1: Trace __enter__ method call

    When entering the with block, __enter__ prints 'Start' and returns 'Resource', assigned to m.
  2. Step 2: Trace inside with block and __exit__ call

    Inside the block, print(m) outputs 'Resource'. After block ends, __exit__ prints 'End'.
  3. Final Answer:

    Start Resource End -> Option C
  4. Quick Check:

    Execution order = __enter__, block, __exit__ [OK]
Quick Trick: Prints from __enter__, block, then __exit__ [OK]
Common Mistakes:
  • Assuming __exit__ runs before block
  • Confusing return value of __enter__

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes