ProgrammingHardIBM · Deloitte pattern
What is printed?
What is printed?
class D:
def __getitem__(self, key):
if isinstance(key, slice):
return f"slice {key.start}:{key.stop}:{key.step}"
return f"item {key}"
d = D()
print(d[3])
print(d[1:5:2])- A. item 3 slice 1:5:2
- B. 3 1:5:2
- C. item 3 TypeError
- D. slice 3 slice 1:5:2
Correct answer: A. item 3 slice 1:5:2
d[3] passes the plain integer 3 as key. d[1:5:2] passes a slice object whose .start, .stop and .step attributes are 1, 5, 2, which __getitem__ detects with isinstance and formats accordingly.
More Python Programming questions
- What is printed? python try: try: 1 / 0 except ZeroDivisionError: raise RuntimeError("r") except RuntimeError as e: print(e…
- What is printed? python try: raise ValueError("x") from None except ValueError as e: print(e.cause, e.suppresscontext)
- What is printed? python try: try: raise KeyError("k") except ValueError: print("vl") except KeyError: print("kl")
- What is printed? python x = 5 print(f"{x=}")
- What is printed? python print(f"{'hi':>10}|") print(f"{'hi':<10}|") print(f"{'hi':^10}|")
- What is printed? python print(f"{10 / 3:.3f}") print(f"{10 // 3}") print(f"{2 10:,}")