ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
class A:
    def __init__(self):
        self.x = 1
    def __enter__(self):
        return self
    def __exit__(self, *a):
        self.x = 0
        return False
with A() as a:
    print(a.x)
print(a.x)
  1. A. 1 1
  2. B. 0 0
  3. C. 1 0
  4. D. 0 1

Correct answer: C. 1 0

Inside the with-block, x is still 1 as set by __init__. After the block ends, __exit__ runs and resets a.x to 0; since 'a' stays bound after the with-statement, the second print sees the updated value 0.

More Python Programming questions

Exams that ask this topic