ProgrammingHardProduct-company MCQ pattern
What is printed?
What is printed?
class N:
def __init__(self, v):
self.v = v
def __bool__(self):
return self.v != 0
n1 = N(0)
n2 = N(5)
print(bool(n1), bool(n2))
if n1:
print("n1 true")
else:
print("n1 false")- A. True False n1 true
- B. False True n1 false
- C. True True n1 true
- D. False False n1 false
Correct answer: B. False True n1 false
__bool__ defines truthiness directly: n1.v is 0 so bool(n1) is False, n2.v is 5 so bool(n2) is True. The if statement calls __bool__ on n1 too, taking the else branch and printing 'n1 false'.
More Python Programming questions
- What is printed? python class Base: def repr(self): return "Base" class Sub(Base): pass print([Sub(), Sub()])
- What is printed? python class CM3: def enter(self): return 42 def exit(self, et, ev, tb): return False with CM3() as val: print(val)
- What is printed? python from contextlib import contextmanager @contextmanager def cm(): print("setup") yield 1 print("teardown") with cm()…
- What is printed? python class A: def enter(self): print("A enter"); return self def exit(self, a): print("A exit") class B: def…
- 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 +…