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)- A. 1 1
- B. 0 0
- C. 1 0
- 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
- What is printed? python class R: @property def x(self): return 5 r = R() try: r.x = 10 except AttributeError: print("AttributeError")
- What is printed? python try: raise TypeError("t") except (ValueError, TypeError) as e: print("caught", type(e).name)
- What is printed? python def f(): return 1, 2, 3 a, b, c = f() print(a, b, c) x = f() print(type(x), x)
- What is printed? python d = {"a": 1, "b": 2} print({v: k for k, v in d.items()})
- What is printed? python s1 = {1, 2, 3} s2 = {2, 3, 4} print(s1 - s2, s1 | s2, s1 & s2)
- What is printed? python print(all([1, 2, 3]), all([1, 0, 3]), any([0, 0, 0]), any([0, 1, 0]))