ProgrammingHardProduct-company MCQ pattern
What is printed?
What is printed?
class A:
def __enter__(self):
print("A enter"); return self
def __exit__(self, *a):
print("A exit")
class B:
def __enter__(self):
print("B enter"); return self
def __exit__(self, *a):
print("B exit")
with A(), B():
print("body")- A. A enter B enter body A exit B exit
- B. A enter B enter body B exit A exit
- C. B enter A enter body A exit B exit
- D. A enter B enter body B exit
Correct answer: B. A enter B enter body B exit A exit
Multiple context managers in one with-statement enter left to right (A then B) and exit in the REVERSE order (B then A), just like nested with-blocks.
More Python Programming questions
- What is printed? python class A: def who(self): return "A" class B(A): def who(self): return "B" class C(A): def who(self): return "C"…
- What is printed? python class A: def f(self): return 1 class B(A): def f(self): return 2 + super().f() class C(B): def f(self): return 3 +…
- What is printed? python class F: @staticmethod def add(a, b): return a + b @classmethod def create(cls): return cls() print(F.add(2, 3)) f…
- What is printed? python class H: slots = ["a", "b"] h = H() h.a = 1 try: h.c = 2 except AttributeError: print("AttributeError") print(h.a)
- What is printed? python class K: x = 10 def method(self): x = 20 return x print(K().method(), K.x)
- What is printed? python class Counter: def init(self, n): self.n = n def iter(self): self.i = 0 return self def next(self): if self.i >=…